JavaScript form events (Part 2)

Table of contents

8. keydown: Triggered when the user presses any key on the keyboard.

9. Keyup: Triggered when the user releases a key on the keyboard.

10. keypress: Triggered when the user presses a character key on the keyboard.

11. focusin: Triggered when a form element or its sub-elements gain focus.

12. Focusout: Triggered when a form element or its sub-elements lose focus.

13. cut: Triggered when the user cuts the text in the text box or text area.

14. copy: Triggered when the user copies the text in the text box or text area.

15. Paste: Triggered when the user pastes text into the text box or text area.


Continuing from the previous article, let’s continue to talk about common form events in JavaScript.

8. keydown: Triggered when the user presses any key on the keyboard.

The keydown event is triggered when the user presses any key on the keyboard. It is suitable for scenarios that require real-time response to keyboard input. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>按键检测</title>
</head>
<body>
  <input type="text" id="myInput" placeholder="按下任意键查看键码" />

  <script>
    var input = document.getElementById('myInput');
    input.addEventListener('keydown', function(event) {
      // 在按键按下时执行特定的操作
      var keyCode = event.keyCode;
      console.log('按下的键码:', keyCode);
    });
  </script>
</body>
</html>

In the above example, we listened to the keydown event of the text input box and obtained the pressed keycode in the event handler function. Through the event.keyCode property, we can get the currently pressed keyboard key code. In this example, we simply output the pressed keycode to the console. You can add custom operations to the keydown event according to specific needs, such as executing different logic based on different key codes, processing special keys or shortcut keys, etc.

9. Keyup: Triggered when the user releases a key on the keyboard.

The keyup event is triggered when the user releases any key on the keyboard. It is suitable for scenarios that require real-time response to keyboard input. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>按键检测</title>
</head>
<body>
  <input type="text" id="myInput" placeholder="松开任意键查看键码" />

  <script>
    var input = document.getElementById('myInput');
    input.addEventListener('keyup', function(event) {
      // 在按键释放时执行特定的操作
      var keyCode = event.keyCode;
      console.log('释放的键码:', keyCode);
    });
  </script>
</body>
</html>

In the above example, we listened to the keyup event of the text input box and obtained the released key code in the event handler function. Through the event.keyCode property, we can get the currently released keyboard key code. In this example, we simply print the released keycode to the console. You can add custom operations to the keyup event according to specific needs, such as executing different logic based on different key codes, processing special keys or shortcut keys, etc.

10. keypress: Triggered when the user presses a character key on the keyboard.

The keypress event is used in JavaScript to respond to the pressing and continuous pressing of keyboard keys. It is suitable for form input and processing user keystrokes. Here's a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>表单键盘事件</title>
</head>
<body>
  <form>
    <input type="text" id="myInput" placeholder="在文本框中输入内容" />
    <button type="button" id="myButton">点击我</button>
  </form>

  <script>
    var input = document.getElementById('myInput');
    var button = document.getElementById('myButton');
    input.addEventListener('keypress', function(event) {
      // 按下键盘时实时响应
      console.log('按键编码:', event.keyCode);
      console.log('按键字符:', String.fromCharCode(event.keyCode));
    });
    button.addEventListener('click', function() {
      // 获取文本框中的值并进行操作
      var value = input.value;
      console.log('文本框的值:', value);
    });
  </script>
</body>
</html>

In this example, we are listening for the keypress event on the text input box in the form. Whenever the user presses any key on the keyboard, the event handler will respond in real time and output the key code and corresponding character. We use event.keyCode to get the key code, and use String.fromCharCode(event.keyCode) to convert the code to the corresponding character.

Additionally, we are listening for click events on the buttons in the form. When the user clicks the button, the event handler gets the value in the text box and operates on it. You can replace the button click operation with other customized logic according to actual needs.

11. focusin: Triggered when a form element or its sub-elements gain focus.

The focusin event is used in JavaScript to respond to the operation of obtaining focus on a form element, including the form element itself and its sub-elements. It is similar to the focus event, but has bubbling characteristics and will be triggered when the child element gains focus.

When using JavaScript's focusin event, it can play a role in the following scenarios:

  1. 1. Form verification: When the input field in the form gets focus, you can use the focusin event to verify in real time whether the content entered by the user meets the requirements. For example, when the user clicks on the input box, check whether the input content is empty or meets specific format requirements.
  2. 2. Auto-complete/suggestion function: When the user enters content in the input box, the focusin event can be used to trigger the auto-complete or suggestion function to provide relevant options or suggestions based on part of the content entered by the user.
  3. 3. Custom style effect: By using the focusin event, you can implement a custom style effect to highlight the form element currently receiving focus. For example, change the background color, border style, or add shadow effects of the input box.
  4. 4. Form element interaction: In a form, when the user switches focus to different input fields, the focusin event can be used to dynamically display or hide other related content or elements based on the field where the current focus is.
  5. 5. Keyboard shortcuts: Use the focusin event to monitor the focus change of a form element and trigger specific keyboard shortcut operations. For example, when the user presses a specific shortcut key in the input box, the corresponding operation can be performed or a specific event can be triggered.

Here's a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>表单焦点事件</title>
</head>
<body>
  <form>
    <input type="text" id="myInput" placeholder="输入姓名" />
  </form>

  <script>
    var input = document.getElementById('myInput');
    input.addEventListener('focusin', function() {
      console.log('表单元素获取焦点');
      input.style.backgroundColor = 'lightblue';
    });

    input.addEventListener('focusout', function() {
      console.log('表单元素失去焦点');
      input.style.backgroundColor = 'white';
    });
  </script>
</body>
</html>

12. Focusout: Triggered when a form element or its sub-elements lose focus.

When using JavaScript's focusout event, it can play a role in the following scenarios:

  1. 1. Form verification: When the input field in the form loses focus, you can use the focusout event to verify in real time whether the content entered by the user meets the requirements. For example, when the user leaves the input box, check whether the input content is empty or meets specific format requirements.
  2. 2. Auto-save: When the user leaves the input field in the form, the focusout event can be used to trigger the auto-save function and save the user's input content to a local or remote server to prevent data loss.
  3. 3. Instant feedback: By using the focusout event, the instant feedback function can be realized, providing relevant feedback information or displaying verification results based on the content entered by the user or the field left. For example, when leaving the input box, check whether the length of the input content meets the requirements, and display the corresponding prompt on the page.
  4. 4. Input assistance: When the user leaves the input field, the focusout event can be used to provide input assistance. For example, check whether the content entered by the user contains specific characters or formats, and provide suggestions or automatic corrections if it does not meet the requirements.

Here is a simple example that demonstrates how to use the focusout event to verify whether the content in the input box is empty:

<!DOCTYPE html>
<html>
<head>
  <title>Focusout Event Example</title>
</head>
<body>
  <form>
    <label for="name">Name:</label>
    <input type="text" id="name" required>
    <button type="submit">Submit</button>
  </form>

  <script>
    const nameInput = document.getElementById('name');

    nameInput.addEventListener('focusout', function(event) {
      if (nameInput.value.trim() === '') {
        alert('Name field cannot be empty!');
      }
    });
  </script>
</body>
</html>

In the above example, the focusout event is triggered when the user leaves the input box (name field). In the event handler, we check whether the value in the input box is empty. If it is empty, a prompt box pops up to remind the user to enter their name. This allows for instant validation of input.

13. cut: Triggered when the user cuts the text in the text box or text area.

The usage scenario of the cut event in a form usually involves processing or providing feedback to the user's operation of cutting text. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>Cut Event Example</title>
</head>
<body>
  <input type="text" id="input-field" placeholder="Enter text to cut">

  <script>
    const inputField = document.getElementById('input-field');

    inputField.addEventListener('cut', function(event) {
      const cutText = event.clipboardData.getData('text/plain');
      alert(`You have cut the text: ${cutText}`);
    });
  </script>
</body>
</html>

In the above example, we created an input box (<input> element). When the user cuts the text in the input box, the cut event will be triggered. In the event handler, we use event.clipboardData.getData('text/plain') to get the clipped text content and provide feedback through a popup box to display the user's clipped text.

Note that the cut, copy, and paste events are all triggered before the text is cut/copied/pasted, so the text content can be obtained in the event handler and further processed or provided with corresponding feedback.

14. copy: Triggered when the user copies the text in the text box or text area.

The usage scenarios of copy events in forms usually involve processing or providing feedback when the user copies text. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>Copy Event Example</title>
</head>
<body>
  <input type="text" id="input-field" placeholder="Enter text to copy">

  <script>
    const inputField = document.getElementById('input-field');

    inputField.addEventListener('copy', function(event) {
      const copiedText = inputField.value.substring(inputField.selectionStart, inputField.selectionEnd);
      alert(`You have copied the text: ${copiedText}`);
    });
  </script>
</body>
</html>

In the above example, we created an input box (<input> element). When the user copies the text in the input box, the copy event will be triggered. In the event handler, we use: inputField.value.substring(inputField.selectionStart, inputField.selectionEnd)

to obtain the copied text content and provide feedback through a pop-up box to display the text copied by the user.

15. Paste: Triggered when the user pastes text into the text box or text area.

The usage scenarios of paste events in forms usually involve processing or providing feedback when the user pastes text. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>Paste Event Example</title>
</head>
<body>
  <input type="text" id="input-field" placeholder="Paste text here">

  <script>
    const inputField = document.getElementById('input-field');

    inputField.addEventListener('paste', function(event) {
      const pastedText = event.clipboardData.getData('text');
      alert(`You have pasted the text: ${pastedText}`);
    });
  </script>
</body>
</html>

In the above example, we created an input box (<input> element). When the user pastes text into the input box, the paste event will be triggered. In the event handler, we use event.clipboardData.getData('text') to get the pasted text content and provide feedback through a popup box to display the text pasted by the user.

Please note that due to security restrictions, access to clipboard data may be restricted, so pasted text content may not be available in some browsers.

Guess you like

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