Preventing Form Submission on ENTER Keypress
In web applications, the ENTER key is often used to submit a form. However, sometimes it's desirable to prevent a form from submitting on ENTER keypress. Below are two methods to achieve this:
Method 1: Onkeypress Handler
This method uses the onkeypress event handler on the form. By creating a function that checks whether the pressed key is ENTER (key code 13) and allowing the form submission only if it's not ENTER, we can prevent immediate form submission. The code for this approach is:
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;
Method 2: Event Delegation with Modern JavaScript
A more modern approach using ES20xx and event delegation involves setting a keypress listener on the entire document. This method checks if the form containing the target input has a special attribute indicating that ENTER keypress should submit the form. The relevant JavaScript and HTML code:
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; } } }
<form>
Both these methods effectively prevent a form from submitting on ENTER keypress while allowing textarea input, which naturally uses ENTER for line breaks, to function normally.
The above is the detailed content of How to Stop a Form from Submitting on ENTER Keypress?. For more information, please follow other related articles on the PHP Chinese website!