Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...