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

yiytaume  于 2023-05-17  发布在  jQuery
关注(0)|答案(3)|浏览(107)

我现在有一个脚本,它将检查一个选择框的值,然后在它旁边启用一个文本字段,然后希望设置焦点。
我现在有这个,它在启用输入字段时工作得很好...

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

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

});

老实说,我有点卡在'focus'上,我试过“$(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"); }

});

各位有什么想法吗?我真的坚持这一点,这将是一个非常简单,但非常有用的除了我的网页建设!
谢谢

irlmq6kh

irlmq6kh1#

还找到了一个不错的小插件来获取下一个输入: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;
    });
};
tf7tbtn2

tf7tbtn22#

修改了上面的答案,缓存了这个jq对象。也不需要接下来内部的过滤器。next()只会返回下一个同级。过滤器基本上是说,只有当它是一个输入或任何过滤器,你给我下一个。如果您确定下一个是所需的对象,则不需要包括过滤器。

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

hmae6n7t3#

我认为你的问题可能是不可能将焦点设置为禁用的输入控件(至少在某些浏览器/操作系统中)。
您的focus()调用基本上是在错误的块中-它应该在else块中,而不是if块中。
就像这样:

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

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

相关问题