使用Enter键移动到输入

时间:2012-04-12 21:46:32

标签: javascript jquery forms input enter

是否可以使用回车键移动到表单中的下一个输入字段?我也想使用标签,但输入键也很好。

仅供参考 - 我确实有几个textareas,我需要在输入时使用回车键返回。这会是冲突吗?

谢谢。 埃里克

2 个答案:

答案 0 :(得分:6)

如果要将一个名为“TabOnEnter”的类添加到要循环的字段中,请输入。

$(document).on("keypress", ".TabOnEnter" , function(e)
  {
    //Only do something when the user presses enter
    if( e.keyCode ==  13 )
    {
       var nextElement = $('[tabindex="' + (this.tabIndex+1)  + '"]');
       console.log( this , nextElement ); 
       if(nextElement.length )
         nextElement.focus()
       else
         $('[tabindex="1"]').focus();  
    }   
  });

//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut();  })

不像以前的答案那么可爱,但它现在有效:

http://jsfiddle.net/konijn_gmail_com/WvHKA/

这样您就可以使用标准HTML功能(tabindex)来确定循环顺序。隐藏的元素应该删除它们的tabindex。

答案 1 :(得分:0)

在黑暗中拍摄(假设你的textareas排成一行):

$(".myTextareas").keypress(function(e) {
    if(e.which == 13) {
        $(this).next('.myTextareas').focus();
    }
});