Home > Web Front-end > JS Tutorial > body text

How Can I Prevent Form Submission When Pressing the Enter Key?

Mary-Kate Olsen
Release: 2024-11-27 00:00:18
Original
479 people have browsed it

How Can I Prevent Form Submission When Pressing the Enter Key?

Prevent Form Submission with the Enter Key

When working with forms, it can be frustrating when pressing the Enter key triggers submission instead of executing a desired JavaScript function. To resolve this, it's necessary to prevent the form from submitting in response to the Enter keypress.

One effective method is to utilize JavaScript's event listener. By attaching a function to the keypress event, you can handle the keypress behavior and prevent the form from submitting. Here's how to do it:

document.addEventListener("keypress", function(e) {
  if (e.keyCode == 13) {
    // Call the desired JavaScript function here
    // ...
    
    // Prevent form submission
    e.preventDefault();
  }
});
Copy after login

In this code:

  • document.addEventListener listens for the "keypress" event.
  • e.keyCode == 13 checks if the pressed key is the Enter key.
  • If the Enter key is pressed, the desired JavaScript function is executed.
  • e.preventDefault() prevents the form from submitting.

By implementing this code, you can disable form submission when the Enter key is pressed and redirect the action to a custom JavaScript function instead.

The above is the detailed content of How Can I Prevent Form Submission When Pressing the Enter Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template