我想在javascript中选择/取消选中所有复选框。
这是我的脚本,但它不起作用:
<form id="labels">
<input type="checkbox">
<input type="checkbox" id="select_all">
</form>
<script>
$('#select_all').click(function()
{
if($("#select_all").is(':checked'))
{
$("form#labels input[type='checkbox']").prop('checked', false);
}else{
$("form#labels input[type='checkbox']").prop('checked', true);
}
});
</script>
答案 0 :(得分:3)
使用.change
事件 - 并参考this
- 您也可以将其缩短一点:
$('#select_all').change(function() {
$("form#labels input[type='checkbox']").prop('checked', this.checked);
});
答案 1 :(得分:1)
您应该更换true
和false
布尔值。
$('#select_all').click(function() {
if($("#select_all").is(':checked')) {
$("form#labels input[type='checkbox']").prop('checked', true);
}else{
$("form#labels input[type='checkbox']").prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="labels">
<input type="checkbox" />
<input type="checkbox" id="select_all" />
</form>
它也可以简化为
$('#select_all').click(function(){
$("#labels input[type='checkbox']").prop('checked', this.checked);
});
$('#select_all').click(function(){
$("#labels input[type='checkbox']").prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="labels">
<input type="checkbox" />
<input type="checkbox" id="select_all" />
</form>