# 5.5 表單事件及停止元素預設行為

## 透過事件物件來停止預設行為

寫法：

```javascript
e.preventDefault();
```

## 範例：連結

連結本身的預設行為是開啟連結，但因為某些情況下，不方便改成其它結構，那就可以先透過 JS 來停止其「開啟連結」這樣的預設行為。例：

![](/files/-MFTkSDDPFyDB8vs__F_)

{% embed url="<https://codepen.io/carlos411/pen/jOqyYJP>" %}

## 練習：表單

需建立網頁檔來測試。

通常欄位上的資料，在送出前，都要先經過驗證，例如欄位必填，如果使用者未填資料，就要先停掉「資料送出」的預設行為。

### 表單的 submit 事件

html：

```markup
<form action="#" method="get" id="my_form">
  <input type="text" id="my_text">
  <button type="submit">資料送出</button>
</form>
```

JS: 表單的 submit  事件：

```javascript
var my_form = document.getElementById("my_form");
my_form.addEventListener("submit", function(e){
  // 資料送出時，執行這裡的程式
});
```

### 表單的停止預設行為

例：

{% embed url="<https://codepen.io/carlos411/pen/jOqyYRP>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.webmix.cc/javascript-web/5.-shi-jian/5.7-ting-zhi-yuan-su-yu-she-hang-wei.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
