Prevent Web Form Submission with ENTER Key
Preventing the ENTER keypress from triggering form submission is a common requirement in web development. Here's how you can implement this behavior in a web-based application:
Solution:
To disable form submission upon ENTER keypress while preserving textarea behavior, use the following code:
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; }
Then, add a keypress handler to the form:
document.querySelector('form').onkeypress = checkEnter;
Alternative Approach (Modern):
A more modern approach using event delegation is as follows:
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; } } }
In this case, HTML elements can be annotated with data-enter-for-submit="1" to selectively allow ENTER-based form submission.
The above is the detailed content of How to Prevent Form Submission with the ENTER Key?. For more information, please follow other related articles on the PHP Chinese website!