Form Submission Prevention on Enter Key Press
Preventing form submission when pressing the Enter key ensures that the focus remains on the current field and allows for JavaScript functions to be triggered instead. The solution involves handling the keypress event and conditionally preventing submission based on the entered key's code.
Implementation
In HTML, add the onkeypress attribute to the form element. This attribute should call a JavaScript function that checks the key code. In the example below, the runScript function is executed on the scriptBox text input:
<form onkeypress="return runScript(event)"> <input>
The runScript function examines the key code of the event. If the code matches the Enter key (typically 13), the function returns false, preventing the form submission.
function runScript(e) { if (e.keyCode == 13) { // Invoke your JavaScript function here... return false; } else { return true; } }
Note:
While keyCode is deprecated in modern browsers, it remains widely supported. However, it's recommended to consider using alternative methods such as key or which for broader compatibility.
The above is the detailed content of How to Prevent Form Submission on Enter Key Press?. For more information, please follow other related articles on the PHP Chinese website!