Home >Web Front-end >JS Tutorial >How to Prevent Unwanted Form Submissions on ENTER Keypress in Web Applications?
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.
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;
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; } } }
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!