2011-12-30 10 views
0

私の元のjavascriptた。このような設定に使用されたjQueryの/ Javascriptを次の表に、すべてのチェックボックスをチェックし

$(document).ready(function(){ 
$("th :checkbox").change(function() { 
    $(this).closest("table").find(":checkbox").prop("checked", $(this).is(":checked")); 
}); 
}); 

:私は少し変わっ

<div> 
<table id="table" width="100%"> 
<tr> 
    <th><input type="checkbox" />Select All</th> 
    <th>A</th> 
    <th>B</th> 
    <th>C</th> 
    <th>D</th> 
</tr> 
<tr> 
    <td><input type="checkbox" /></td> 
    <td>A</td> 
    <td>B</td> 
    <td>C</td> 
    <td>D</td> 
</tr> 
</table> 
</div> 

どのように私のテーブルであり、

<table> 
<tr> 
    <th><input type="checkbox" />select all</th> 
</tr> 
</table> 
<table> 
<tr> 
    <td><input type="checkbox" /></td> 
</tr> 
<tr> 
    <td><input type="checkbox" /></td> 
</tr> 
</table> 

のチェックボックスをオンにするとがチェックされている場合は、次の表の<td>のチェックボックスがすべてオンになっていますか?

ありがとうございました。

Related to this post.

答えて

2

.closest("table").next()を追加:

$(document).ready(function(){ 
$("th :checkbox").change(function() { 
    $(this).closest("table").next().find(":checkbox").prop("checked", $(this).is(":checked")); 
}); 
}); 

$(this).closest("table")th :checkboxに一致する要素のテーブルを選択します。 next()は、この場合、別のテーブルである次の要素を選択します。

このコードは簡単に破損する可能性があります。私は、別のテーブルにIDを設定し、次のコードを使用することをお勧めします:

$(document).ready(function(){ 
$("th :checkbox").change(function() { 
    $("#id-of-table :checkbox").prop("checked", $(this).is(":checked")); 
}); 
}); 
+0

テーブルはMySQLのデータから生成されます。それでも動作するのでしょうか? –

+0

*テーブル*または*行*?表が1つしかない場合、コードは機能します。そうでなければ、あなたは '$(this).closest(" table ")。nextAll(" table ")'を使う必要があります。 –

+0

Gotcha。ありがとう、@ロブW.あなたは大きな助けをしてきました。 –

関連する問題