Home > Web Front-end > JS Tutorial > How Can I Prevent Form Submission on Enter Key Press and Execute Custom JavaScript Instead?

How Can I Prevent Form Submission on Enter Key Press and Execute Custom JavaScript Instead?

Susan Sarandon
Release: 2024-12-04 15:11:10
Original
871 people have browsed it

How Can I Prevent Form Submission on Enter Key Press and Execute Custom JavaScript Instead?

Preventing Form Submission on Enter Key Press

When a user presses the Enter key within a form, the default behavior is to submit the form. However, some scenarios require preventing form submission and executing a custom JavaScript function instead.

To achieve this, the event listener on the form can be modified to handle the Enter key press. Here's how it can be done:

document.querySelector("form").addEventListener("keypress", (e) => {
  if (e.key === "Enter") {
    // Prevent form submission
    e.preventDefault();

    // Call your JavaScript function
    customFunction();
  }
});

function customFunction() {
  // Your custom JavaScript function logic
}
Copy after login

In this example, the form submission is prevented by calling e.preventDefault() within the event handler. By adding this condition and calling the custom function, the Enter key triggers the customFunction() instead of submitting the form.

Note:

Modern browsers recommend using e.key instead of e.keyCode. However, for compatibility with older browsers, using both might be necessary.

The above is the detailed content of How Can I Prevent Form Submission on Enter Key Press and Execute Custom JavaScript Instead?. 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