[英]jquery set all checkbox checked
I am using jquery 1.11.1 and this is my code: 我使用的是jquery 1.11.1,这是我的代码:
$("#rowchkall").change(function(){
if($(this).is(':checked')){
$("input:checkbox[class=rowchk]").each(function() {
alert("set checked");
$(this).attr('checked', "checked");
});
}else{
$("input:checkbox[class=rowchk]").each(function() {
$(this).attr('checked', false);
});
}
});
When I first click on #rowchkall
, all the checkbox is set to checked. 当我第一次点击
#rowchkall
,所有复选框都设置为选中。 When I click it again, all checkbox is unchecked. 当我再次单击它时,将取消选中所有复选框。
When I click it again, alert box still appear but none of the checkbox will be checked. 当我再次单击它时,仍会出现警告框,但不会选中任何复选框。 Why is it only work for first time only?
为什么它只在第一次工作? How can I fix it?
我该如何解决?
Thank you. 谢谢。
Use .prop()
instead of .attr()
使用
.prop()
代替.attr()
$(this).prop('checked', true); //true to check else false uncheck
Your code can be simplified as 您的代码可以简化为
$("#rowchkall").change(function () {
$("input:checkbox.rowchk").prop('checked',this.checked);
});
A Good Read .prop() vs .attr() A Good Read .prop()vs .attr()
$("#rowchkall").change(function(){
if($(this).is(':checked')){
$("input.rowchk[type=checkbox]").each(function() {
alert("set checked");
$(this).attr('checked',true);
});
}else{
$("input.rowchk[type=checkbox]").each(function() {
$(this).attr('checked', false);
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.