AaronLS AaronLS - 6 months ago 15
Javascript Question

Change Enter from submission to Tab?

Users don't like the fact that the Enter key submits the page. So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

I have tried many javascript snippets found on the net but none have worked so far. The only one that has even come close to having an effect was e.preventDefault() of the jQuery API, which stops the submit, but nothing I have tried emulates the tab behavior.

e.returnValue = false;
e.cancel = true;


Page still submits with the above in the keydown event handler. Same effect with
return false
in the keydown event handler. The handler is firing, tested by putting a breakpoint in it with firebug.

This needs to work with both IE and Firefox.

Don't say "don't do this".

1) I'm already convinced that I shouldn't do it, but it's not a choice that is mine, so the discussion is mute.

2) It would be an answer to the question "Should I do this?", which is not the question that I am asking.

Answer

This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:

Here's a simple example:

$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).next("input").focus();
    }
});

Example: http://jsfiddle.net/andrewwhitaker/Txg65/

Update: If you have elements in between your inputs, using plain next() will not work. Instead, use nextAll():

$("input").bind("keydown", function(event) {
    if (event.which === 13) {
        event.stopPropagation();
        event.preventDefault();
        $(this).nextAll("input").eq(0).focus();
    }
});

http://jsfiddle.net/andrewwhitaker/GRtQY/

Comments