سؤال

I have a couple of text inputs in which hitting the enter key should move to the next one and after the last text input finally the submit button should have the focus without being pressed. Jumping from input to input by enter works fine with this:

$("input.insert").keydown(function (event) {
    if(event.keyCode == 13) {
        $("input.insert").eq($("input.insert").index(this) + 1).focus(); 
    }
});

But when the cursor is in the last text input field just ahead of the submit button and I hit enter the focus jumps to the submit button and releases its click event. Why? I want the user to hit enter again after leaving the last input field.

Thank you very much in advance for your help.

هل كانت مفيدة؟

المحلول

It's hard to say exactly what is happening with your code without seeing the rest of it, but I'm sure that adding the event.preventDefault() line will solve your problem. It basically stops the browser from carring out the default action for the event see example http://jsfiddle.net/3m4eL/

$('input[type="text"]').keydown(function (event) {
    if (event.keyCode == 13) {
        $("input").eq($("input").index(this) + 1).focus();
        event.preventDefault();
    }
});

Note that I've only bound the function to the keydown event of the text inputs, and not the submit input - otherwise you can't submit the form at all

note that event.preventDefault() does not exist natively in Internet Explorer prior to version 9, but jQuery adds the missing function for you and uses event.returnValue = false as a fallback

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top