Preventing Form Submission on Enter Key Press
When a user presses the Enter key within a form, the default behavior is to submit the form. However, some scenarios require preventing form submission and executing a custom JavaScript function instead.
To achieve this, the event listener on the form can be modified to handle the Enter key press. Here's how it can be done:
document.querySelector("form").addEventListener("keypress", (e) => { if (e.key === "Enter") { // Prevent form submission e.preventDefault(); // Call your JavaScript function customFunction(); } }); function customFunction() { // Your custom JavaScript function logic }
In this example, the form submission is prevented by calling e.preventDefault() within the event handler. By adding this condition and calling the custom function, the Enter key triggers the customFunction() instead of submitting the form.
Note:
Modern browsers recommend using e.key instead of e.keyCode. However, for compatibility with older browsers, using both might be necessary.
The above is the detailed content of How Can I Prevent Form Submission on Enter Key Press and Execute Custom JavaScript Instead?. For more information, please follow other related articles on the PHP Chinese website!