Home > Web Front-end > JS Tutorial > How Can I Prevent Form Submission When the Enter Key is Pressed?

How Can I Prevent Form Submission When the Enter Key is Pressed?

Mary-Kate Olsen
Release: 2024-11-26 01:52:09
Original
269 people have browsed it

How Can I Prevent Form Submission When the Enter Key is Pressed?

Avoiding Form Submission on Enter Key Press

In a bid to facilitate a custom function when pressing the Enter key, while evading form submission, it's crucial to disable the form's default submission behavior.

Solution:

To achieve this, intercept the Enter key event by defining an event listener:

if(characterCode == 13) {
    // Prevent event propagation
    return false; 
} else{
    return true;
}
Copy after login

This code snippet ensures that pressing the Enter key doesn't propagate the event further, effectively preventing form submission.

Example:

Consider a form with the following text box:

<input>
Copy after login

To execute a custom script from this text box upon Enter key press without triggering form submission, use this code:

function runScript(e) {
    // Prevent form submission if Enter key is pressed
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}
Copy after login

By returning false from the event listener function, the Enter key event is effectively disabled, allowing the custom script to execute without submission.

Note:

While the use of keyCode is deprecated, it remains a viable option in practice. Moreover, despite the deprecated status of which, it is still commonly used.

The above is the detailed content of How Can I Prevent Form Submission When the Enter Key is Pressed?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template