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

时间:2009-08-05 10:30:02

标签: jquery focus next

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

我现在有这个功能可以正常启用输入字段......

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

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

});

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

});

任何想法请大家好吗?我真的坚持这个,这对我正在建设的页面来说是一个非常简单但非常有用的补充!

由于

3 个答案:

答案 0 :(得分: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;
    });
};

答案 1 :(得分: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();
    }
});

答案 2 :(得分:1)

我认为您的问题可能是无法将焦点设置为禁用的输入控件(至少在某些浏览器/操作系统中)。

您的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(); }
});