表单事件

Frontend SELF ZH
第 9 级, 课程 3
可用

9.1 表单的基本事件

要让表单功能正常工作,咱们得搞清楚并且管理用户与表单元素互动时发生的事件。下面咱们会详细讲解 HTML 表单中最常用的事件,以及用 JavaScript 处理这些事件的方式,还会有一些例子。

在 HTML 中,表单可以触发各种事件,比如用户和输入框、按钮、复选框以及单选按钮互动时发生的事件。以下是表单的主要事件:

  • submit — 表单提交事件
  • reset — 表单重置事件
  • focus — 元素获取焦点事件
  • blur — 元素失去焦点事件
  • change — 表单项值改变事件
  • input — 表单项输入事件
  • select — 表单项文本选取事件

9.2 submit 事件

submit事件 在表单提交时触发。一般是用户点击表单中的 "提交" 按钮时触发的。处理这个事件可以用来在数据传到服务器之前做校验,阻止提交包含错误的表单,也可以用来实现其他操作。

submit事件处理示例:

HTML
    
        <form id="my-form" action="/submit" method="post">
          <label for="username">用户名:</label>
          <input type="text" id="username" name="username">
          <button type="submit">提交</button>
        </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');

      form.addEventListener('submit', function(event) {
        const username = document.getElementById('username').value;
        if (username === '') {
          alert('请填写用户名。');
          event.preventDefault(); // 阻止表单提交
        } else {
          alert(`用户名已收到: ${username}`);
          event.preventDefault();
        }
      });
    
  
JavaScript
    
      const form = document.getElementById('my-form');

      form.addEventListener('submit', function(event) {
        const username = document.getElementById('username').value;
        if (username === '') {
          alert('请填写用户名。');
          event.preventDefault(); // 阻止表单提交
        }
      });
    
  

9.3 reset 事件

reset事件 在表单重置到初始状态时触发。一般用户点击 "重置" 按钮时触发。处理这个事件可以用来在重置表单时做一些额外操作,比如清空错误提示信息。

reset事件处理示例:

HTML
    
      <div style="min-height: 220px">
        <form id="my-form">
          <label for="name">名字:</label>
          <br>
          <input type="text" id="name" name="name">
          <br><br>
          <label for="email">邮箱:</label>
          <br>
          <input type="email" id="email" name="email">
          <br><br>
          <label for="password">密码:</label>
          <br>
          <input type="password" id="password" name="password">
          <div style="margin-top: 10px">
            <button id="btn" type="button">重置</button>
          </div>
        </form>
        <p id="log"></p>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="name">名字:</label>
        <br>
        <input type="text" id="name" name="name">
        <br><br>
        <label for="email">邮箱:</label>
        <br>
        <input type="email" id="email" name="email">
        <br><br>
        <label for="password">密码:</label>
        <br>
        <input type="password" id="password" name="password">
        <div style="margin-top: 10px">
          <button type="reset">重置</button>
        </div>
      </form>
      <p id="log"></p>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const btn = document.getElementById('btn');
      const n = document.getElementById('name');
      const e = document.getElementById('email');
      const p = document.getElementById('password');
      const log = document.getElementById('log');

      document.addEventListener('DOMContentLoaded', () => {
        n.value = "John";
        e.value = "john@mail.com";
        p.value = "qwerty";
      });

      btn.addEventListener('click', () => {
        n.value = "";
        e.value = "";
        p.value = "";
        log.textContent = '表单已被重置!';
      });
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const log = document.getElementById('log');

      form.addEventListener('reset', function () {
        log.textContent = '表单已被重置!';
      });
    
  

9.4 focus 和 blur 事件

focus 和 blur 事件 是当表单元素分别获得和失去焦点时触发的。通常这些事件用于优化用户与表单的交互,比如显示提示或者错误信息。

处理 focus 事件的示例:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="username">用户名:</label>
          <input type="text" id="username" name="username">
          <div id="username-hint" style="display: none;">
            当输入框聚焦时,你会看到这个提示。
            即便切换焦点后,它也会显示。
          </div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username">
        <div id="username-hint" style="display: none;">
          当输入框聚焦时,你会看到这个提示。
          即便切换焦点后,它也会显示。
        </div>
      </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const usernameInput = document.getElementById('username');
      const hint = document.getElementById('username-hint');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      usernameInput.addEventListener('focus', function (event) {
        hint.style.display = 'block';
      });
    
  
JavaScript
    
      const usernameInput = document.getElementById('username');
      const hint = document.getElementById('username-hint');

      usernameInput.addEventListener('focus', function () {
        hint.style.display = 'block';
      });
    
  

处理 blur 事件的示例:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="username">用户名:</label>
          <input type="text" id="username" name="username">
          <div id="username-error" style="display: none; color: red;">
            如果输入框失去焦点后为空,将显示错误信息
          </div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username">
        <div id="username-error" style="display: none; color: red;">
          如果输入框失去焦点后为空,将显示错误信息
        </div>
      </form>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const usernameInput = document.getElementById('username');
      const error = document.getElementById('username-error');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      usernameInput.addEventListener('blur', function (event) {
        error.style.display = usernameInput.value === '' ? 'block' : 'none';
      });
    
  
JavaScript
    
      const usernameInput = document.getElementById('username');
      const error = document.getElementById('username-error');

      usernameInput.addEventListener('blur', function () {
        error.style.display = usernameInput.value === '' ? 'block' : 'none';
      });
    
  

9.5 input事件

input事件 每次表单元素的值发生变化时都会触发,而不管元素是否失去焦点。这个事件经常用于即时验证用户输入,比如实时验证输入字段。

处理input事件的例子:

HTML
    
      <html lang="zh-CN">
        <head>
          <style>
            input {
              outline: none;
            }

            .valid {
              border-color: green;
            }

            .invalid {
              border-color: red;
            }

            .wrapper-valid::after {
              content: "Email有效";
              margin-left: 5px;
              color: green;
            }

            .wrapper-invalid::after {
              content: "Email无效";
              margin-left: 5px;
              color: red;
            }
          </style>
        </head>
        <body>
          <form id="my-form">
            <label for="email">Email:</label>
            <div id="wrapper">
              <input type="email" id="email" name="email">
            </div>
          </form>
        </body>
      </html>
    
  
JavaScript
    
      const form = document.getElementById('my-form');
      const inputWrapper = document.getElementById('wrapper');
      const emailInput = document.getElementById('email');

      form.addEventListener("submit", (event) => {
        event.preventDefault();
      });

      emailInput.addEventListener('input', function () {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (emailPattern.test(emailInput.value)) {
          inputWrapper.classList.add('wrapper-valid');
          inputWrapper.classList.remove('wrapper-invalid');
          emailInput.classList.add('valid');
          emailInput.classList.remove('invalid');
        } else {
          inputWrapper.classList.add('wrapper-invalid');
          inputWrapper.classList.remove('wrapper-valid');
          emailInput.classList.add('invalid');
          emailInput.classList.remove('valid');
        }
      });
    
  
JavaScript
    
      const emailInput = document.getElementById('email');
      const inputWrapper = document.getElementById('wrapper');

      emailInput.addEventListener('input', function () {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (emailPattern.test(emailInput.value)) {
          emailInput.classList.add('valid');
          emailInput.classList.remove('invalid');
        } else {
          emailInput.classList.add('invalid');
          emailInput.classList.remove('valid');
        }
      });
    
  

9.6 select 事件

select 事件 当用户在表单元素中选择文本时触发,比如在输入框或者文本框中。 这个事件可以用来在选择文本时执行某些操作,比如显示复制按钮。

处理 select 事件的示例:

HTML
    
      <div style="min-height: 55px">
        <form id="my-form">
          <label for="text-input">输入文字:</label>
          <input type="text" id="text" name="text">
          <div id="select-message"></div>
        </form>
      </div>
    
  
HTML
    
      <form id="my-form">
        <label for="text-input">输入文字:</label>
        <input type="text" id="text" name="text">
        <div id="select-message"></div>
      </form>
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('my-form');
        const textInput = document.getElementById('text');
        const selectMessage = document.getElementById('select-message');

        form.addEventListener("submit", (event) => {
          event.preventDefault();
        });

        textInput.addEventListener('select', function () {
          selectMessage.textContent = '你选中了文本!';
        });
      });
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const textInput = document.getElementById('text');
        const selectMessage = document.getElementById('select-message');

        textInput.addEventListener('select', function () {
          selectMessage.textContent = '你选中了文本!';
        });
      });
    
  

9.7 change事件

change事件发生在表单元素的值改变后,并且用户离开该元素(失去焦点)时。这个事件通常用于检测表单字段的变化,比如下拉列表或复选框。

处理change事件的例子:

HTML
    
      <form id="my-form">
        <label for="color-select">选择颜色:</label>
        <select id="color-select" name="color">
          <option value="red">红色</option>
          <option value="green">绿色</option>
          <option value="blue">蓝色</option>
        </select>
      </form>
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('my-form');
        const selectElement = document.getElementById('color-select');

        form.addEventListener("submit", (event) => {
          event.preventDefault();
        });

        selectElement.addEventListener('change', function () {
          alert('你选择了颜色: ' + selectElement.value);
        });
      });
    
  
JavaScript
    
      document.addEventListener('DOMContentLoaded', function () {
        const selectElement = document.getElementById('color-select');

        selectElement.addEventListener('change', function () {
          alert('你选择了颜色: ' + selectElement.value);
        });
      });
    
  
1
任务
Frontend SELF ZH, 第 9 级, 课程 3
已锁定
重置表单
重置表单
1
任务
Frontend SELF ZH, 第 9 级, 课程 3
已锁定
提示
提示
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION