选中全部复选框

时间:2014-04-22 07:59:04

标签: jquery html checkbox

这是我的代码:

<SCRIPT language="javascript">
$(function () {
 $("#selectall").click(function () {
  $('.name').attr('checked', this.checked);
 });

    $(".name").click(function () {
     if ($(".name").length == $(".name:checked").length) {
       $("#selectall").attr("checked", "checked");
     } else {
       $("#selectall").removeAttr("checked");
     }
     });
     });
</SCRIPT>

以及表格:

<td><input type="checkbox" id="selectall"/></td>
<td>No.</td>
<td class="web" width="400" align="center">Name</td>
<td class="web" width="240" align="center">Username</td>

我的问题是,当我点击selectall复选框时,它不会检查所有复选框。

1 个答案:

答案 0 :(得分:0)

看看:http://jsfiddle.net/3s7KC/

$("#selectall").click(function () {
 $('.name').attr('checked', this.checked);
});

$(".name").click(function () {
 if ($(".name").length == $(".name:checked").length) {
   $("#selectall").attr("checked", "checked");
 } else {
   $("#selectall").removeAttr("checked");
 }
});

<input type="checkbox" id="selectall"/> Select All
<table>
<tr>
    <td><input type="checkbox" id="1" class="name"/></td>
    <td>No.</td>
    <td class="web" width="100" align="center">Name</td>
    <td class="web" width="140" align="center">Username</td>
</tr>
<tr>
    <td><input type="checkbox" id="2" class="name"/></td>
    <td>No.</td>
    <td class="web" width="100" align="center">Name</td>
    <td class="web" width="140" align="center">Username</td>
</tr>
</table>

我添加了一些额外的HTML代码来测试pouposes。

相关问题