jquery實現checkbox的單選和全選
一、思路
全選:判斷“全選”checkbox的狀態,如果選中則把tbody下所有的checkbox選中,反之
單選:主要是判斷有沒有全選,如果不是選中狀態就把全選的checkbox狀態設置為false,如果是選中就拿所有選中狀態下“name=id”的chekbox和所有‘’name=id"的數量去比較,如果一樣表示全選了,設置全選的chekbox為選中狀態,反之。
二、代碼
1.css部分,直接搬運的django項目里面的。
<table border="2" style="margin: 0 auto;text-align: left;width: 800px">
<thead>
<tr>
<th><input type="checkbox" name="all">全選</th>
<th>id</th>
<th>用戶名</th>
<th>昵稱</th>
<th>郵箱</th>
<th>角色</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tb">
{% for user in userlist %}
<tr>
<td><input type="checkbox" name="id" value="{{ user.UserID }}" onclick="userCheck(this)"></td>
<td>{{ user.UserID }}</td>
<td>{{ user.Username }}</td>
<td>{{ user.NickName }}</td>
<td>{{ user.Email }}</td>
<td>{{ user.Role.RoleName }}</td>
<td>
<img id="update" src="/static/img/edit-new.png" onclick="getUser({{ user.UserID }})">
<img id="delete" src="/static/img/edit_remove.png" onclick="userdelete({{ user.UserID }})">
</td>
</tr>
{% endfor %}
</tbody>
</table>
2.js部分,name和id都可以根據實際修改
$(function () {
//全選,設置chheckbox name='all' tbody id=tb
$("input[name=all]").click(function () {
if (this.checked) {
$("#tb :checkbox").prop("checked", true);
} else {
$("#tb :checkbox").prop("checked", false);
}
});
});
//單選 設置name=id
function userCheck(ths) {
if (ths.checked == false) {
$("input[name=all]:checkbox").prop('checked', false);
}
else {
var count = $("input[name='id']:checkbox:checked").length;
if (count == $("input[name='id']:checkbox").length) {
$("input[name=all]:checkbox").prop("checked", true);
}
}
}

