2011-09-05 56 views
2

我有很多這樣的輸入字段的形式,查找下一個輸入框,並將焦點,如果它是jQuery的空阱

http://jsfiddle.net/WPDF9/1/

我試圖循環具有名稱distanceSlabCost

元素
$(":text[name^=distanceSlabCost]").each(function(i){ 
    var curTxtBox = $(this); 
    var nextTxtBox =  // find the next text field (?) 
    var nextTxtFieldId  // find the id of next text field (?) 

}); 

如何獲取下一個textField元素的id? 另外,如果下一個字段的值爲空,則將焦點設置爲該字段。

+0

http://stackoverflow.com/questions/7305100/filter-elements-by-class-name- and-value-jquery/7305125#7305125 – NimChimpsky

回答

0

只是一個想法可能通過class = .distance_slab通過容器div並使用next()獲取以下容器div,它是子元素(children())。

0

我沒有測試過下面的代碼,但它應該工作:

var fields = $(":text[name^=distanceSlabCost]"); 

for (var i=0; i<fields.length; i++) { 
    var curTxtBox = fields[i]; 
    var nextField = i+1 <= fields.length-1 ? fields[i+1] : null; 
    var nextId = nextField ? nextField.attr("id") : null; 
} 

我希望這會幫助你;)

PS:這種方法的好處是,你必須查詢只有一次!

+0

http://jsfiddle.net/WPDF9/1/ null null – Hussy

+0

把這個小提琴引用到我的實際代碼中http://jsfiddle.net/WPDF9/1/ – Hussy

0

我希望我猜中了:

$(":text[name^=distanceSlabCost]").each(function(i){ 
    var curTxtBox = $(this), 
     nextTxtBox = curTxtBox.next('input[type=text]'), 
     nextTxtFieldId = nextTxtBox.attr('id'); 

    if(nextTxtBox.val() === '') { 
     nextTxtBox.focus(); 
    } 
}); 
+0

http:// jsfiddle .net/95rqY/21 /給出未定義的錯誤 – Hussy

+0

最後一個Textfield沒有下一個。檢查'if(nextTxtFieldId === undefined)...' – binarious

+0

http://jsfiddle.net/WPDF9/1/將此小提琴引用爲實際代碼 – Hussy

0

你可以這樣做:

$(":text[name^=distanceSlabCost]").each(function(i){ 
    var curTxtBox = $(this); 
    var nextTxtBox = curTxtBox.next('input:text');  // find the next text field (?) 
    var nextTxtFieldId = nextTxtBox.attr('id'); // find the id of next text field (?) 

}); 
+0

http://jsfiddle.net/95rqY/21/ – Hussy

+0

其給予nextTxtBox = undefined – Hussy

+0

你在你的小提琴中有很多錯別字,現在它的作品http://jsfiddle.net/95rqY/22/與我的代碼 –