30

I have some textboxes on a .net-page and want to achieve the following with jQuery: if the user presses return, the program should behave "as if" he had used the tab key, thus, selecting the next element. I tried the following code (and some more):

<script type="text/javascript">

jQuery(document).ready(function () {

    $('.tb').keypress(function (e) {
        if (e.keyCode == 13)
        {
            $(this).trigger("keydown", [9]);
            alert("return pressed");
        } 
    });
});

<asp:TextBox ID="TextBox1" runat="server" CssClass="tb"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" CssClass="tb"></asp:TextBox>

but it just does not work! Missing something, making a mistake?

Here some links I used

here

and here

4

4 回答 4

19

尝试这个:

http://jsbin.com/ofexat

$('.tg').bind('keypress', function(event) {
  if(event.which === 13) {
    $(this).next().focus();
  }
});

或循环版本:http: //jsbin.com/ofexat/2

于 2012-02-09T16:03:44.137 回答
12

我创建了一个简单的 jQuery 插件来解决这个问题。它使用 jQuery UI 的 ':tabbable' 选择器来查找下一个 'tabbable' 元素并选择它。

示例用法:

// Simulate tab key when enter is pressed           
$('.tb').bind('keypress', function(event){
    if(event.which === 13){
        if(event.shiftKey){
            $.tabPrev();
        }
        else{
            $.tabNext();
        }
        return false;
    }
});
于 2013-09-11T12:06:24.597 回答
11

从多个答案中,我为我组合了完美的解决方案,其中 enter 充当输入和选择的选项卡,并专注于下一个输入、选择或文本区域,同时允许在文本区域内输入。

 $("input,select").bind("keydown", function (e) {
     var keyCode = e.keyCode || e.which;
     if(keyCode === 13) {
         e.preventDefault();
         $('input, select, textarea')
         [$('input,select,textarea').index(this)+1].focus();
     }
 });
于 2014-12-31T11:18:54.387 回答
4

尝试这个

$(this).trigger({
    type: 'keypress',
    which: 9
});
于 2012-02-09T15:58:53.607 回答