将焦点设置为jQuery中的下一个输入?

Nic*_*ick 7 jquery focus next

我目前有一个脚本,它将检查选择框的值,然后在它旁边启用一个文本字段,然后希望设置焦点.

我现在有这个在启用输入字段时工作正常...

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true);  }
    else { $(this).next('input').removeAttr("disabled"); }

});
Run Code Online (Sandbox Code Playgroud)

说实话,我有点卡在'焦点'位上,我试过"$(this).next('input').focus();" 但这根本没有集中注意力,虽然它没有引起Javascript错误......

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); $(this).next('input').focus(); }
    else { $(this).next('input').removeAttr("disabled"); }

});
Run Code Online (Sandbox Code Playgroud)

伙计们好吗?我真的坚持这个,这对我正在建设的页面来说是一个非常简单但非常有用的补充!

谢谢

Tim*_*olo 15

还找到了一个很好的小插件来获取下一个输入:http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select').not(':hidden');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        else {fields.first().focus();}
        return false;
    });
};
Run Code Online (Sandbox Code Playgroud)

  • 我会在字段声明中添加`.not(':hidden')`,因此只选择可见元素.另外,添加`else {fields.first().focus();}`以使焦点环绕到第一个元素. (4认同)

red*_*are 5

用缓存的这个jq对象修改了上面的答案.此外,不需要下面的过滤器.next()只会返回下一个兄弟.过滤器基本上是说如果它是输入或你提供的任何过滤器,只能让我接下来.如果您确定下一个是所需对象,则无需包含过滤器.

$("#assessed select").change(function () {
    var $this = $(this);
    if( $this.val() === 'null') {
        $this.next()
             .attr("disabled", true);
    }
    else {
        $this.next()
             .removeAttr("disabled")
             .focus();
    }
});
Run Code Online (Sandbox Code Playgroud)