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
Linda HamiltonOriginal
2024-11-07 15:08:02238browse

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;

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;
    }
  }
}

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!

Statement:
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