Home > Web Front-end > JS Tutorial > How to Prevent Unwanted Form Submissions on ENTER Keypress in Web Applications?

How to Prevent Unwanted Form Submissions on ENTER Keypress in Web Applications?

Linda Hamilton
Release: 2024-11-07 15:08:02
Original
274 people have browsed it

How to Prevent Unwanted Form Submissions on ENTER Keypress in Web Applications?

Prevent Web Form Submission on ENTER Keypress

In web-based applications, inadvertent form submissions triggered by the ENTER key can be a nuisance. This guide provides solutions to prevent such unwanted behavior.

Solution 1: Custom Keypress Handler

A custom keypress handler can be implemented for the form to intercept the ENTER key press and prevent form submission for all elements except textareas.

function checkEnter(e) {
  e = e || event;
  var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
  return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
document.querySelector('form').onkeypress = checkEnter;
Copy after login

Solution 2: Event Delegation with Modern JavaScript

A more modern approach using event delegation can be employed to handle ENTER presses. This approach involves capturing the event at the document level and checking for the closest form ancestor. Only designated elements with the data-enter-for-submit attribute will trigger form submission on ENTER.

document.addEventListener(`keypress`, handle);

function handle(evt) {
  const form = evt.target.closest(`#testForm`);
  if (form) {
    if (evt.target.dataset.enterForSubmit) {
      if (evt.key === `Enter`) {
        evt.preventDefault();
        return logClear(`won't submit "${evt.target.value}"`);
      }
      return true;
    }
  }
}
Copy after login

Additional Notes

  • Textareas should be handled differently, as pressing ENTER within a textarea typically signifies a line break.
  • The code snippets provided are customizable and can be adapted to specific application needs.

The above is the detailed content of How to Prevent Unwanted Form Submissions on ENTER Keypress in Web Applications?. 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