如何通过选中/取消选中一个复选框来选中和取消选中 html 表中的所有复选框? [英] how to check and uncheck all checkboxes in an html table with checking/unchecking one check box?
本文介绍了如何通过选中/取消选中一个复选框来选中和取消选中 html 表中的所有复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表格,有行,每一行都有一个复选框,thead
处有一个主复选框.我的代码:
I have a table, with rows, every row has a check box, and there is a main check box at the thead
. My code:
<table border="1">
<thead>
<tr>
<th><input type="checkbox" id="allcb" name="allcb"/></th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id="cb1" name="cb1"/></td>
<td>value1</td>
</tr>
<tr>
<td><input type="checkbox" id="cb2" name="cb2"/></td>
<td>value2</td>
</tr>
<tr>
<td><input type="checkbox" id="cb3" name="cb3"/></td>
<td>value3</td>
</tr>
</tbody>
</table>
(也可以试试这里)
谁能帮助我,如果我选中顶部的主要复选框,将选中所有复选框,如果我取消选中主要复选框,则所有复选框都将取消选中.如果你帮助我,谢谢你!
Could anyone help me, how to do that if I check the main check box at the top, all check boxes will be checked, if I uncheck the main, all checkboxes will be unchecked. Thank you if you help me!
推荐答案
Working Demo http://jsfiddle.net/xYAfj/2/
Working Demo http://jsfiddle.net/xYAfj/2/
$('#allcb').change(function(){
if($(this).prop('checked')){
$('tbody tr td input[type="checkbox"]').each(function(){
$(this).prop('checked', true);
});
}else{
$('tbody tr td input[type="checkbox"]').each(function(){
$(this).prop('checked', false);
});
}
});
更短的代码
工作演示 http://jsfiddle.net/cse_tushar/4tss8/
$('#allcb').change(function () {
$('tbody tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
这篇关于如何通过选中/取消选中一个复选框来选中和取消选中 html 表中的所有复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文