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

在jQuery中将焦点设置为下一个输入?,jquery,focus,next,Jquery,Focus,Next,我现在有一个脚本,它将检查一个选择框的值,然后在它旁边启用一个文本字段,然后希望设置焦点 我现在有这个功能,可以很好地启用输入字段 $("#assessed select").change(function () { if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); } else { $(this).next('input').removeAttr("disabled");

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

我现在有这个功能,可以很好地启用输入字段

$("#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"); }

});
有什么好主意吗?我真的被困在这一点上,这将是一个非常简单的,但非常有用的除了我正在建设的网页


谢谢

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

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

已使用缓存的此jq对象修改了上述答案。此外,不需要next内的过滤器。next()将只返回下一个兄弟。过滤器基本上是说,只有当它是一个输入或任何过滤器,你给我下一个。如果确定下一个对象是所需对象,则无需包含过滤器

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

还找到了一个很好的小插件来获取下一个输入:

$.fn.focusnePutfield=函数(){
返回此值。每个(函数(){
var fields=$(this).parents('form:eq(0),body')。find('button,input,textarea,select')。not(':hidden');
var index=fields.index(本);
如果(索引>-1&&(索引+1)
你也可以发布你的HTML吗?哈!非常感谢Rob。。。我刚刚意识到我把重点放在了“如果”而不是“其他”!绝对的学生错误,对不起,非常感谢-直到你发布我才意识到:)记住缓存$(这个)而不是多次调用它绝对完美,是一个比我使用的更好的解决方案,谢谢!我会将
.not(':hidden')
添加到字段声明中,因此只选择可见元素。另外,添加
else{fields.first().focus();}
将焦点环绕到第一个元素。为什么要先查找父窗体:eq(0)?@Serge它选择输入元素所在的父窗体。我不知道“eq(0)”是否是必需的,而不是我的代码tho,所以我不确定。好主意@collik-我已经添加了它。inI还将向字段声明添加一个
。not(':disabled')
,因此只选择非禁用元素。
$.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;
    });
};