最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to go to next textbox when enter is pressed? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked May 7, 2014 at 7:34 user3563036user3563036 291 gold badge1 silver badge6 bronze badges 3
  • and what have you tried so far?? – Milind Anantwar Commented May 7, 2014 at 7:34
  • press tab and not enter :) – defau1t Commented May 7, 2014 at 7:35
  • Try to read some books about, before trying something. – Farhad Jabiyev Commented May 7, 2014 at 7:35
Add a ment  | 

4 Answers 4

Reset to default 2

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

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

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(); });

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" />
发布评论

评论列表(0)

  1. 暂无评论