user3563036
user3563036

Reputation: 29

How to go to next textbox when enter is pressed?

Hi guys I'm learning Javascript and I would like to ask you guys how can I go to the next textbox after inputing text when I press the enter button in the keyboard. thank you

Upvotes: 0

Views: 17549

Answers (4)

Gary Hayes
Gary Hayes

Reputation: 1788

You can go to the next field in many ways, as demonstrated by all the answers here, but don't forget to assign the order of what is actually NEXT as well. You can go from field to field with the TAB button, and the layout of your site may not always go in the order you'd expect or want. The solution to this is to add tabindex="" to your fields as such:

<input type="text" tabindex="1" />
<input type="password" tabindex="2" />
<input type="submit" value="Log In" tabindex="3" />

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

I've developed a plugin to include enter event.

(function ($) {
    $.fn.enter = function (func) {
        this.bind('keypress', function (e) {
            if (e.keyCode == 13) func.apply(this, [e]);
        });
        return this;
    };
})(jQuery);

You can call it like this:

$('#input1').enter(function(){ $(this).next().focus(); });

Upvotes: 0

Felix
Felix

Reputation: 38102

You can use .keyup() to keep track of when user finish key in a character and e.keyCode to get which key was pressed, if it's 13(means enter) then use .focus() to focus the next textbox element:

$('input[type="textbox"]').keyup(function(e) {
    if(e.keyCode == 13) {
        $(this).next().focus();
    }
});

Fiddle Demo

Upvotes: 2

Sandy
Sandy

Reputation: 817

Try this code :

 $('#inputform').on('keydown', 'input', function (event) {
  if (event.which == 13) {
    event.preventDefault();
    var $this = $(event.target);
    var index = parseFloat($this.attr('data-index'));
    $('[data-index="' + (index + 1).toString() + '"]').focus();
 }

});

Help Link

Upvotes: 0

Related Questions