Javascript 简明教程

JavaScript - Form Events

Form Events

JavaScript 中的表单事件与 HTML 表单相关。当用户与文本字段、按钮、复选框等表单元素交互时,这些事件会由用户操作触发。表单事件允许你针对这些操作执行 JavaScript 代码,从而能够验证表单数据、对表单提交或重置执行操作并增强用户体验。

The form events in JavaScript are events that are associated with HTML forms. These events are triggered by user actions when interacting with form elements like text fields, buttons, checkboxes, etc. Form events allow you to execute JavaScript code in response to these actions, enabling you to validate form data, perform actions on form submission or reset, and enhance the user experience.

JavaScript 表单事件挂接到文档对象模型(也称为 DOM)中的元素上,默认情况下使用冒泡传播,即从底部(子元素)到顶部(父元素)。

JavaScript form events are hooked onto the elements in the Document Object Model also known as DOM where by default the bubbling propagation is used i.e. from bottom (children) to top(parent).

List of Common Form Events

以下是部分常用表单事件:

Here are some common form events:

Form Event

Description

onsubmit

Triggered when a form is submitted. It’s often used for form validation before data is sent to the server.

onreset

Triggered when the form is reset, allowing you to perform actions when the user resets the form.

onchange

Triggered when the value of a form element (input, select, textarea) changes. Commonly used for user input validation or dynamic updates.

oninput

Triggered immediately when the value of an input element changes, allowing for real-time handling of user input.

onfocus

Triggered when an element receives focus, such as when a user clicks or tabs into an input field. Useful for providing feedback or enhancing the user experience.

onblur

Triggered when an element loses focus, such as when a user clicks outside an input field or tabs away. Useful for validation or updates triggered by loss of focus.

Examples

Example: The onchange Event

下面提供的示例展示了 onchange 事件的功能。该事件在用户更改下拉列表 (<select>) 选项选择时激活。函数 handleChange 会动态修改一个 <h2> 元素,以显示新选择的国家;从而在用户首选项发生变化时提供即时反馈。

The provided instance below illustrates the functionality of the onchange event. This event activates upon a user’s alteration in dropdown (<select>) option selection. The function, handleChange, dynamically modifies an <h2> element to display the newly selected country; thus offering immediate feedback as user preferences evolve.

<!DOCTYPE html>
<html>
<body>
   <label for="country">Select a country:</label>
   <select id="country" onchange="handleChange()">
      <option value="USA">USA</option>
      <option value="Canada">Canada</option>
      <option value="UK">UK</option>
      <option value="India">India</option>
   </select>
   <p id="txt"></p>
   <script>
      function handleChange() {
         // Perform actions when the dropdown selection changes
         var selectedCountry = document.getElementById('country').value;
         document.getElementById("txt").textContent=
		 "Selected country: "+selectedCountry;
     }
   </script>
</body>
</html>

Example: The onsubmit Event

以下示例重点介绍了 onsubmit 事件在提交表单时的功能。该表单包含用户名字段和密码字段;在调用 validateForm 函数时,必须同时填写这两个字段才能通过验证。通过此验证后,提交表单会触发显示一条确认消息。

The following example highlights the onsubmit event’s functionality upon form submission. The form features a username field and password field; both must be filled for successful validation when invoking the validateForm function. Upon passing this validation, submitting the form will trigger display of a confirmation message.

<!DOCTYPE html>
<html>
<body>
   <form onsubmit="return validateForm()">
      <label for="username">Username:</label>
      <input type="text" id="username" name="username" required>
      <label for="password">Password:</label>
      <input type="password" id="password" name="password" required>
      <br/>
      <input type="submit" value="Submit">
   </form>
   <script>
      function validateForm() {
         var username = document.getElementById('username').value;
         var password = document.getElementById('password').value;
         // Perform validation
         if (username === "" || password === "") {
            alert("Please fill in all fields");
            return false; // Prevent form submission
         }
         alert("Form submitted! Username is:"+username+",Password is:"+password);
         return true; // Allow form submission
      }
   </script>
</body>
</html>

Example: The onreset event

在这个演示中,我们观察了 onreset 事件的作用:它在用户点击表单中的“重置”按钮时触发。一旦调用 resetForm 函数,它就会清除用户填写的表单内容,然后显示一个警告,以确认该表单已成功重置。

In this demonstration, we observe the onreset event in action: it triggers upon the user’s click of the "Reset" button within a form. The resetForm function once invoked, clears the form content filled by user and then displays an alert to confirm successful reset of said form.

<!DOCTYPE html>
<html>
<body>
   <form onreset="resetForm()">
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>
      <input type="reset" value="Reset">
   </form>
   <script>
      function resetForm() {
         // Perform actions when the form is reset
         alert("Form has been reset!");
      }
   </script>
</body>
</html>

Example: The oninput Event

此示例展示了 oninput 事件:当用户在搜索输入字段中输入时——一个真正的实时操作!handleInput 函数被触发;它将每个当前搜索输入直接记录到屏幕上。

This example illustrates the oninput event: as the user types into the search input field a real-time action, indeed! The handleInput function triggers; it logs each current search input directly to screen.

<!DOCTYPE html>
<html>
<body>
   <label for="search">Search:</label>
   <input type="text" id="search" oninput="handleInput()">
   <div id="message" style=" margin-top: 10px; font-weight: lighter;border: 1px solid #ddd;padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-family: 'Arial', sans-serif; font-size: 14px; color: #333; width: 30%;"></div>

   <script>
      var messageElement = document.getElementById('message');
      function handleInput() {
         // Perform actions as the user types
         var searchInput = document.getElementById('search').value;
         messageElement.innerHTML+="Search input: " + searchInput+'<br>';
      }
   </script>
</body>
</html>

Example: onfocus and onblur Events

在这个示例中,onfocus 和 onblur 事件合并在一起。用户在输入字段中聚焦会触发对 handleFocus 函数的调用,然后该函数会将一条消息记录到控制台中。相反,在点击输入字段外部内容或通过 Tab 键切换走时——此操作会触发另一个名为 handleBlur 的函数的执行,该函数随后会记录一条切换的消息,同样记录在该控制台中。

The onfocus and onblur events merge in this example. The user’s focus on the input field triggers a call to the handleFocus function, which then logs a message into the console. In contrast, when clicks outside of or tabs away from said input field – this action triggers execution of another function called handleBlur that subsequently records an alternative message within that same console log.

<!DOCTYPE html>
<html>
<body>
   <label for="name">Name:</label>
   <input type="text" id="name" onfocus="handleFocus()" onblur="handleBlur()">
   <p id= "output"></p>
   <script>
      const output = document.getElementById('output');
      function handleFocus() {
         // Perform actions when the input gets focus
         output.innerHTML += "Input has focus" + "<br>";
      }
      function handleBlur() {
         // Perform actions when the input loses focus
         output.innerHTML += "Input lost focus" + "<br>";
      }
   </script>
</body>
</html>