表格checkbox全選以及單選jquery實現:
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th><input type="checkbox" value="" name="all-user"></th>
<th>id</th>
<th>名稱</th>
</tr>
</thead>
<tbody>
{% for i in objects %}
<tr class="gradeX">
<td><input type="checkbox" value="{{ i.id }}" name="one-user" onclick="userCheck(this)"></td>
<td>{{ i.id }}</td>
<td>{{ i.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
// 全選
$("input[name=all-user]").click(function () {
if (this.checked) {
$("input[name=one-user]").prop("checked", true);
} else {
$("input[name=one-user]").prop("checked", false);
}
});
// 單選的時候去掉全選狀態
function userCheck(ths) {
if (ths.checked === false) {
$("input[name=all-user]:checkbox").prop('checked', false);
}
else {
var count = $("input[name=one-user]:checkbox:checked").length;
if (count === $("input[name=one-user]:checkbox").length) {
$("input[name=all-user]:checkbox").prop("checked", true);
}
}
}