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

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

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

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

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

谢谢

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

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

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

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

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