Preventing Form Submission on ENTER Keypress
In web-based applications, preventing the ENTER key from submitting a form ensures that the form is only submitted when the user explicitly clicks the submit button. This approach enhances the user experience and prevents accidental form submissions.
To prevent the ENTER key from triggering form submission, you can employ the following code snippet:
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; }
Once you have defined the checkEnter function, you can attach it as a keypress handler to the form:
<form [...] onkeypress="return checkEnter(event)">
Alternatively, you can use the following ES20xx approach:
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; } } }
This approach uses event delegation to prevent form submission when the ENTER key is pressed, allowing the user to input multi-line text in textarea elements without triggering submission.
The above is the detailed content of How to Prevent Form Submission on Enter Keypress?. For more information, please follow other related articles on the PHP Chinese website!