Home > Web Front-end > JS Tutorial > How to Prevent Form Submission on Enter Key Press?

How to Prevent Form Submission on Enter Key Press?

Barbara Streisand
Release: 2024-11-26 09:07:12
Original
628 people have browsed it

How to Prevent Form Submission on Enter Key Press?

Form Submission Prevention on Enter Key Press

Preventing form submission when pressing the Enter key ensures that the focus remains on the current field and allows for JavaScript functions to be triggered instead. The solution involves handling the keypress event and conditionally preventing submission based on the entered key's code.

Implementation

In HTML, add the onkeypress attribute to the form element. This attribute should call a JavaScript function that checks the key code. In the example below, the runScript function is executed on the scriptBox text input:

<form onkeypress="return runScript(event)">
  <input>
Copy after login

The runScript function examines the key code of the event. If the code matches the Enter key (typically 13), the function returns false, preventing the form submission.

function runScript(e) {
  if (e.keyCode == 13) {
    // Invoke your JavaScript function here...

    return false;
  } else {
    return true;
  }
}
Copy after login

Note:

While keyCode is deprecated in modern browsers, it remains widely supported. However, it's recommended to consider using alternative methods such as key or which for broader compatibility.

The above is the detailed content of How to Prevent Form Submission on Enter Key Press?. 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