如何使用jQuery将焦点移动到下一个输入?

Mat*_*att 49 jquery autocomplete

我使用自动完成插件与jQuery,它工作正常.但是,在IE中,当用户选择自动完成中的项目时,焦点不会移动到下一个输入字段.当然它适用于Firefox.该插件没有内置解决方案,但确实提供了"选项".有没有办法可以强制它移动到下一个输入字段?

Nic*_*ver 92

你可以这样做:

$("input").change(function() {
  var inputs = $(this).closest('form').find(':input');
  inputs.eq( inputs.index(this)+ 1 ).focus();
});
Run Code Online (Sandbox Code Playgroud)

这里发布的其他答案可能不适合您,因为它们依赖于下一个输入是下一个兄弟元素,而事实并非如此.此方法前进到表单并搜索下一个输入类型元素.

  • 'input:visible,select:visible'工作得更好,找到选择框并跳过隐藏字段. (10认同)
  • 请参阅此答案:http://stackoverflow.com/questions/7303507/simulating-the-tab-keydown-focusing-next-element-as-determined-by-tabindex,因为它考虑了tabindex,因为它将由真正的浏览器 (3认同)

小智 29

JQuery UI已经有了这个,在我下面的例子中我包含了一个maxchar属性,专注于下一个可聚焦元素(输入,选择,文本区域,按钮和对象),如果我输入最大字符数

HTML:

text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
    <option value="1">1</option>
    <option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
    <option value="1">1</option>
    <option value="1">2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

Javascript:

$(function() {
    var focusables = $(":focusable");   
    focusables.keyup(function(e) {
        var maxchar = false;
        if ($(this).attr("maxchar")) {
            if ($(this).val().length >= $(this).attr("maxchar"))
                maxchar = true;
            }
        if (e.keyCode == 13 || maxchar) {
            var current = focusables.index(this),
                next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
            next.focus();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 这个答案怎么这么少的赞成?您可以从$(function(){,down to,})逐字复制和粘贴; 并且一旦输入字段已满,它就会移动到下一个字段,并在用户完成时记录输入字段.如此普遍和自足.谢谢! (2认同)

ant*_*ant 11

Sam的意思是:

$('#myInput').focus(function(){
    $(this).next('input').focus();
})
Run Code Online (Sandbox Code Playgroud)


bus*_*ssa 7

尝试使用类似的东西:

            var inputs = $(this).closest('form').find(':focusable');
            inputs.eq(inputs.index(this) + 1).focus();
Run Code Online (Sandbox Code Playgroud)

  • 提醒一下,我没有意识到 :focusable 伪选择器需要 jQuery UI 插件,以防其他人在尝试使用它时出错。 (3认同)
  • 优雅简洁。真的很好的代码!如果您希望导航模拟键盘输入行为,*:tabbable* 可能是比 *:focusable* 更好的选择。 (2认同)

小智 5

为什么不简单地将输入字段放在要跳转到id的位置并进行简单的聚焦

$("#newListField").focus();
Run Code Online (Sandbox Code Playgroud)

  • 它对于制作通用解决方案没有用. (4认同)

Sam*_*Sam 1

您能发布一些 HTML 作为示例吗?

同时,试试这个:

$('#myInput').result(function(){
    $(this).next('input').focus();
})
Run Code Online (Sandbox Code Playgroud)

这是未经测试的,所以可能需要一些调整。