[英]Checkbox to select all rows in a table
我在一張桌子里面有一張桌子。 基本結構如下
<input type="checkbox" name="CheckAll" id="CheckAll"/> <b>Click to select all Option Values</b>
<table class="Parent">
<tr>
<td><input type="checkbox" id="Parent">Parent1</td>
<td><table class="Children">
<tr><td><input type="checkbox" id="Child">Child1</td></tr>
<tr><td><input type="checkbox" id="Child">Child2</td></tr>
<tr><td><input type="checkbox" id="Child">Child3</td></tr>
<td>
</tr>
<tr>
<td><input type="checkbox" id="Parent">Parent2</td>
<td><table class="Children">
<tr><td><input type="checkbox" id="Child">Child1</td></tr>
<tr><td><input type="checkbox" id="Child">Child2</td></tr>
<td>
</tr>
當我單擊“全選”(表格上方的復選框)時,我希望選中或取消選中所有復選框。 我做了以下
$(document).ready(function () {
$("#CheckAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
現在我試圖在選擇父母之一時選擇所有孩子。 假設我無權訪問視圖中的父 ID。 如何僅訪問與正在更改的復選框相鄰的表?
您可以通過定位下一個 TD,然后將其包含的表來做到這一點。
請注意,您必須將#Parent
、 #Child
等更改為類,因為您不能有重復的 ID。
$('.Parent[type=checkbox]').on('change', function() {
$(this).closest('td')
.next('td')
.find('table input[type=checkbox]')
.prop('checked', this.checked);
});
嘗試這個,
$(this).parent().next('td').find(':checkbox').prop('checked', this.chekced);
作為旁注,您有更多具有相同 id 的元素,即Parent
,這是錯誤的。 您必須具有唯一的 ID。 您可以使用Parent
類,而不是提供相同的 id。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.