JavaScript form events (Part 1)

Table of contents

1. Input: Triggered when the value of the form element changes, applicable to most form elements.

2. Change: Triggered when the value of the form element changes and loses focus. It is suitable for input boxes, drop-down lists, etc.

3. Submit: Triggered when the form is submitted, applicable to form elements.

4. reset: Triggered when the form is reset, applicable to form elements.

5. Focus: Triggered when the form element gains focus.

6. blur: triggered when the form element loses focus.

7. select: Triggered when the text in the text box or text area is selected.


1. Input: Triggered when the value of the form element changes, applicable to most form elements.

Form event input is often used to monitor changes in input boxes in real time and process them accordingly. It is suitable for scenarios that require immediate response when users input content, such as real-time search, input box character limit, dynamic update of calculation results, etc.

The following is a simple example. When the user enters text in the input box, the number of characters entered is counted in real time and displayed on the page:

<!DOCTYPE html>
<html>
<head>
  <title>实时字符统计</title>
</head>
<body>
  <label for="input-text">输入文本:</label>
  <input type="text" id="input-text">
  <p id="char-count">字符数:0</p>
  <script>
    // 获取输入框和字符统计区域元素
    var inputText = document.getElementById('input-text');
    var charCount = document.getElementById('char-count');
    // 监听input事件
    inputText.addEventListener('input', function() {
      // 获取输入框的值
      var value = inputText.value;
      // 统计字符数
      var count = value.length;
      // 更新字符统计区域的内容
      charCount.textContent = '字符数:' + count;
    });
  </script>
</body>
</html>

2. Change: Triggered when the value of the form element changes and loses focus. It is suitable for input boxes, drop-down lists, etc.

The form event change is suitable for scenarios where you need to monitor changes in form element values ​​and handle them accordingly when the values ​​change. It differs from the input event in that the change event is triggered when the user submits the form or leaves the form element, while the input event is triggered every time the user inputs.

The following is a simple example. When the user selects different options, different prompt information is displayed according to the selected option:

<!DOCTYPE html>
<html>
<head>
  <title>选择提示信息</title>
</head>
<body>
  <label for="select-option">选择选项:</label>
  <select id="select-option">
    <option value="option1">选项1</option>
    <option value="option2">选项2</option>
    <option value="option3">选项3</option>
  </select>
  <p id="message">请选择一个选项</p>
  <script>
    // 获取选择框和提示信息元素
    var selectOption = document.getElementById('select-option');
    var message = document.getElementById('message');
    // 监听change事件
    selectOption.addEventListener('change', function() {
      // 获取选择的值
      var selectedValue = selectOption.value;

      // 根据选择的值显示相应的提示信息
      if (selectedValue === 'option1') {
        message.textContent = '您选择了选项1';
      } else if (selectedValue === 'option2') {
        message.textContent = '您选择了选项2';
      } else if (selectedValue === 'option3') {
        message.textContent = '您选择了选项3';
      }
    });
  </script>
</body>
</html>

3. Submit: Triggered when the form is submitted, applicable to form elements.

The form event submit is suitable for scenarios where you need to perform some operations when the user submits the form. By listening to the submit event, the corresponding processing function can be triggered when the user clicks the submit button or presses the Enter key to submit the form, such as data verification, form submission and other operations.

The following is a simple example that when a user submits a form, the form data is output to the console through the JavaScript submit event:

<!DOCTYPE html>
<html>
<head>
  <title>表单提交</title>
</head>
<body>
  <form id="my-form">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name" required>
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" required>
    <button type="submit">提交</button>
  </form>

  <script>
    var form = document.getElementById('my-form');
    form.addEventListener('submit', function(event) {
      event.preventDefault();
      // 获取表单数据
      var name = document.getElementById('name').value;
      var email = document.getElementById('email').value;
      // 输出表单数据到控制台
      console.log('姓名:', name);
      console.log('邮箱:', email);
    });
  </script>
</body>
</html>

4. reset: Triggered when the form is reset, applicable to form elements.

The reset event is triggered when the form is reset and can be used to perform some reset operations or perform some specific processing when the form is reset. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>表单重置</title>
</head>
<body>
  <form id="my-form">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name" value="John Doe">
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" value="[email protected]">
    <button type="reset">重置</button>
  </form>

  <script>
    var form = document.getElementById('my-form');
    form.addEventListener('reset', function(event) {
      // 在重置表单时执行特定的操作
      console.log('表单已重置');

      // 可以在这里进行一些其他的处理,例如清空输入框内容、恢复默认选项等
    });
  </script>
</body>
</html>

5. Focus: Triggered when the form element gains focus.

The focus event is triggered when a form element gains focus and can be used to perform some specific operations when the user's focus enters the form element. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>表单焦点</title>
</head>
<body>
  <form>
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name">
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email">
    <button type="submit">提交</button>
  </form>

  <script>
    var nameInput = document.getElementById('name');
    var emailInput = document.getElementById('email');
    nameInput.addEventListener('focus', function(event) {
      // 在姓名输入框获取焦点时执行特定的操作
      console.log('姓名输入框获取焦点');
    });
    emailInput.addEventListener('focus', function(event) {
      // 在邮箱输入框获取焦点时执行特定的操作
      console.log('邮箱输入框获取焦点');
    });
  </script>
</body>
</html>

In the above example, we listened to the focus events of the name input box and email input box respectively, and performed some specific operations in the event handler function. In this example, we simply print a message to the console to indicate which input box has the focus. You can add custom operations to the focus event according to specific needs, such as displaying auxiliary tips, changing styles, etc.

6. blur: triggered when the form element loses focus.

The blur event is triggered when a form element loses focus and can be used to perform some specific operations when the user's focus leaves the form element. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>表单失去焦点</title>
</head>
<body>
  <form>
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name">
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email">
    <button type="submit">提交</button>
  </form>

  <script>
    var nameInput = document.getElementById('name');
    var emailInput = document.getElementById('email');
    nameInput.addEventListener('blur', function(event) {
      // 在姓名输入框失去焦点时执行特定的操作
      console.log('姓名输入框失去焦点');
    });
    emailInput.addEventListener('blur', function(event) {
      // 在邮箱输入框失去焦点时执行特定的操作
      console.log('邮箱输入框失去焦点');
    });
  </script>
</body>
</html>

In the above example, we listened to the blur events of the name input box and email input box respectively, and performed some specific operations in the event handling function. In this example, we simply print a message to the console to indicate which input box has lost focus. You can add custom operations to the blur event according to specific needs, such as verifying input content, saving data, etc.

7. select: Triggered when the text in the text box or text area is selected.

The select event is triggered when the user selects text. It is suitable for scenarios that require operations or responses to the selected text. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>文本选择</title>
</head>
<body>
  <p>请在下方文本框内选择一段文本:</p>
  <textarea id="myTextarea" rows="4" cols="50"></textarea>

  <script>
    var textarea = document.getElementById('myTextarea');
    textarea.addEventListener('select', function(event) {
      // 在文本选择发生时执行特定的操作
      var selectedText = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
      console.log('选中的文本:', selectedText);
    });
  </script>
</body>
</html>

In the above example, we listened to the select event of the text box and obtained the selected text in the event handler. By using the textarea.selectionStart and textarea.selectionEnd properties, we can get the starting and ending positions of the selected text, and then use the substring method to extract the selected text. In this example, we simply output the selected text content to the console. You can add custom operations to the select event according to specific needs, such as performing cut, copy, format, etc. operations.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130910291