2009-08-05 82 views
7

我目前已經有了一個腳本來檢查選擇框的值,然後在它旁邊啓用一個文本字段,然後有望設置焦點。將焦點設置爲jQuery中的下一個輸入?

我有這個處是使輸入字段正常工作的那一刻...

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

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

}); 

我有點憋屈「專注」位是誠實的,我試過「$(本)的.next( '輸入')聚焦();」。但這並沒有關注所有,雖然它沒有提出一個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"); } 

}); 

任何想法,請大家?我非常堅持這一點,這將是一個非常簡單但對我正在構建的頁面非常有用的補充!

感謝

+0

你能張貼您的HTML呢? – RaYell 2009-08-05 10:35:19

回答

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(); 
    } 
}); 
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(); } 
}); 
+0

哈!非常感謝羅布......我只是意識到我把重點放在'如果'而不是'其他'! 絕對的小學生錯誤,對不起,很多謝謝 - 直到你發佈,我意識到:) – Nick 2009-08-05 10:36:32

+0

記得緩存$(this),而不是多次調用它 – redsquare 2009-08-05 10:42:27

+0

完成,謝謝:) – Nick 2009-08-05 10:51:15

14

還發現了一個可愛的小插件來獲得下輸入: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; 
    }); 
}; 
相關問題