Prevent Enter Key Submitting Forms With JQuery

Friday, July 15, 2011 - 10:35

A common practice that some users have is to press the enter key when they are filling in forms on the web. This might be when they are just moving to the next field, but the trouble is that this will submit the form.

To prevent this from happening you can simply stop the form being submitted if the enter key had been pressed. This is done by binding a JQuery event to the input elements of the form and returning false if the key pressed is enter, which has the keyCode value of 13. We also include a call to the JQuery method preventDefault() to stop the event propagating.

1
2
3
4
5
6
$('form input').keydown(function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
});

Taking this a step further it might be an idea to try and achieve what the users are expecting and jump the focus to the next element in the form. Due to security restrictions it is impossible to change the key that was pressed to a tab, but the event we are looking for can be easily simulated. All we need to do it find all the input elements in the form, figure out where the current element is and then focus on the next input element (if it exists). The following code does just this.

1
2
3
4
5
6
7
8
9
10
$('form input').keydown(function (e) {
    if (e.keyCode == 13) {
        var inputs = $(this).parents("form").eq(0).find(":input");
        if (inputs[inputs.index(this) + 1] != null) {                    
            inputs[inputs.index(this) + 1].focus();
        }
        e.preventDefault();
        return false;
    }
});
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

You are going to stop people also from pressing Enter on "Submit"?

Change:

$('form input').keydown(function (e) {

to:

$('form input:not([type="submit"])').keydown(function(e) {

thanks for the code , it help me alot, thanks again

I can submit this form bt pressing teh Enter key when in a text input field (i.e if I use the Enter key instead of the tab key to move from one field to the next. I tried to prevent this on my site using teh Jquery on this page but it did not work for me either. Is there a better way ?

Chhers

Richard

I'm starting with jquery and this article has helped me a lot. Thank you for writing it.

Add new comment