[英]How to get all the ids from all the table rows checked?
首先,我創建一個包含 n 行的表,每行都包含一個復選框。 我需要從檢查的所有行中獲取所有 ID。
<body>
<table border='1' style='width:100%'>
<tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
</table>
<button id='test'>Get Checked</button>
</body>
這是我到目前為止得到的:
<script>
$(document).ready(function() {
$('#test').click(function(){
var getID = $(':checkbox:checked').closest('tr').attr('id');
alert(getID);
});
});
</script>
但這只給了我一個 id。 如果我選擇多行,我只會得到第一個選定的 id。 此外,我需要將所有選擇的 id 存儲在一個數組中以備后用。
用戶 jQuery 對此的each
功能。
$(':checkbox:checked').each(function( index ) {
var closestTr = $(this).closest('tr').attr('id');
alert(closestTr);
});
var getID = $(':checkbox:checked').closest('tr').attr('id');
應該:
var getID = $('.checkbox:checked').closest('tr').attr('id');
在 jQuery 中,使用選擇器默認為第一個。 所以,我們應該使用each
get all 選擇器元素。
<script>
$(document).ready(function() {
$('#test').click(function(){
var arrId = [];
$(':checkbox:checked').each(function(){
var id = $(this).closest('tr').attr('id');
arrId.push(id);
})
console.log(arrId);
});
});
</script>
嘗試這樣的事情,在fiddle 中演示。 確保在每個輸入復選框之前添加 open td
JS
$('#test').click(function(){
var ids = $(':checkbox:checked').map(function() {
var id = $(this).closest('tr').prop('id');
alert(id);
return id;
}).get();
alert(ids);
});
HTML
<table border='1' style='width:100%'>
<tr id='1'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='2'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='3'><td>'hi'</td><td><input type='checkbox' /></td></tr>
<tr id='4'><td>'hi'</td><td><input type='checkbox' /></td></tr>
</table>
<button id='test'>Get Checked</button>
把和 id 放在你的桌子上:
<table id="myTab" border='1' style='width:100%'>
為避免在頁面中出現其他復選框,請從表中選擇復選框,例如:
var ids = [];
$('#mytab :checkbox:checked').each(function( index ) {
var closestTr = $(this).closest('tr').attr('id');
ids.push(closestTr);
});
alert(ids);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.