【发布时间】:2014-01-15 17:36:57
【问题描述】:
我正在尝试选中/取消选中所有复选框,这样如果选中/取消选中其中一个复选框,则所有复选框都将被选中/取消选中。
这是我的代码:
HTML:
<th><input type="checkbox" name="pay" id="chkAll" class="chkAll"/>With Pay</th>
<th><input type="checkbox" name="pay" id="chkAll2" class="chkAll2"/>Without Pay</th>
<td><input type="checkbox" name="pay" value="With Pay" class="chk" id="chk"/></td>
<td><input type="checkbox" name="pay" value="Without Pay" class="chk2" id="chk2"/></td>
JS:
$('.chkAll').change(function () {
var id = $(this).attr("id").replace("check_", "");
if ($(this).is(':checked')) {
$(".chk").prop('checked', true);
$(".chk2").prop('checked', false);
$('.chkAll2').prop('checked', false);
} else {
$(".chk").prop('checked', false);
}
});
$('.chkAll2').change(function () {
var id = $(this).attr("id").replace("check_", "");
if ($(this).is(':checked')) {
$(".chk2").prop('checked', true);
$(".chk").prop('checked', false);
$('.chkAll').prop('checked', false);
} else {
$(".chk2").prop('checked', false);
}
});
$('.chk').not('[id^=chkAll]').change(function () {
if ($(this).is(':checked')) {
$('.chkAll').prop('checked', true);
} else {
$('.chkAll').prop('checked', false);
}
});
【问题讨论】:
-
对多个 html 元素使用相同的
id并不好。您应该为此使用class。
标签: javascript jquery checkbox