Engineer Engineer - 24 days ago 7
HTML Question

Move Cursor to next text Field pressing Enter

I have multiple text fields in my form and I want when user enters data in one text field and press enter that the cursor moves to another text-field which is next to current text field. I visited some question but didn't find them useful.

$("#username").keypress(function (event) {
alert("inside function");
if(event.keyCode == 13) {
textboxes = $("input.username");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1];
nextBox.focus();
nextBox.select();
event.preventDefault();
return false;
}
}
});


this is my code which i have tried
an other thing that when the data entered in last text field then the form will submit on mouse click on the button not with enter press.

Answer

This should work:

$(".username").keyup(function (event) {
    if (event.keyCode == 13) {
        textboxes = $("input.username");
        currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 1];
            nextBox.focus();
            nextBox.select();
        }
        event.preventDefault();
        return false;
    }
});

ENTER doesn't trigger keypress in all browsers, used keyup instead. Also attached eventlistener to each input instead of a wrapper.

A live demo at jsFiddle.

Your code with event delegation will also work with a slight change:

currentBoxNumber = textboxes.index(event.target);

this on above sentence would refer to the wrapper instead of the input, event.target refers to the actual element which fired the event.

A live demo at jsFiddle.