2012-10-30 88 views
0

我有一張5 x 5的表格。每個單元格都是一個asp.net文本框。 我想用非空文本框獲取最後一行的5個文本框值。 例如:無法通過jQuery獲取html表格中的兄弟值

enter image description here

這應該讓地獄啊,我FRIE ND

但我得到的所有值,但最後一個(ND)。我不知道爲什麼。這裏是我的代碼:

// RIGHT HERE, $(this) referes to the whole table 
$(this).find('input[value!=""]') 
     // I get the last edited textbox 
     .last() 
     // Go up to the parent <td> 
     .parent('td') 
     .siblings('td') 
     // I get all my brothers of type input 
     .children(':input') 
     .each(function() { 
      alert($(this).val()); 
     }); 

我做錯了什麼,但什麼? 謝謝。

回答

1

問題所在當您撥打.siblings() - 返回全部其他<td>與您當前選擇的<td>元素具有相同父元素的元素。這個問題可以通過遍歷DOM中的另一個步驟來解決,然後像@Adrian,@Quintin Robinson,@Sushanth - 和@wirey所顯示的那樣選擇孩子。

我想我會發佈一個答案,所以你會有一個解釋,因爲所有其他答案解決了你的問題,但沒有解釋什麼是錯的。現在這裏是我將如何改變你的代碼:)

$(this).find('input[value!=""]:last') 
    .parents('tr') 
    .find('td input') 
    .each(function() { 
     alert($(this).val()); 
    }); 
+0

這個工程。謝謝 !! – anmarti

1

您應該使用parents()和搜索tr,然後將所有input裏面:

$(this).find('input[value!=""]') 
     .last() 
     .parents('tr') 
     .find('input') 
     .each(function() { 
      alert($(this).val()); 
     }); 
1

你可以使用這樣的事情..

$(this).find('input[value!=""]:last') 
     .parents("tr:first") 
     .find(":text") 
     .each(...); 
0

試試這個

$(this).find('input[value!=""]') 

     .closest('tr') 
     .prev('tr') 
     .children(':input') 
     .each(function() { 
      alert($(this).val()); 
     }); 
1

你應該這樣做

$(this).find('tr').filter(function() { // find all trs 
    // returns the row if all inputs are filled 
    return $(this).find('input').filter(function() { 
     return $(this).val().length > 0 
    }).length == 5; // check to make sure row has 5 unempty textboxes 
}).last() // get the last tr returned with no empty textboxes 
.find('input').each(function() { // find inputs 
    console.log($(this).val()); 
});​ 

http://jsfiddle.net/E5hnA/

你的問題就出在你不按行過濾..但找到最後unempty文本框..然後開始遍歷有

$(this).find('input[value!=""]') // find all inputs that are not empty 
    .last() // get the last one 

時,有一個輸入會發生什麼在最後一行有一個非空文本框?這就是你所得到的。我在我的例子中做的是。

找到所有行>過濾器,返回那些具有填充所有輸入>獲得的最後一個返回集合中>然後做什麼 - 因爲現在你有最後一行的所有輸入充滿