Let’s start with the html structure
<body><form action=""><input type="checkbox" id="checkedAll">全选/全不选<br><input type="checkbox" name="items" value="足球">足球<input type="checkbox" name="items" value="蓝球">蓝球<input type="checkbox" name="items" value="羽毛球">羽毛球<input type="checkbox" name="items" value="乒乓球">乒乓球<br><input type="button" id="send" value="提交"></form></body>
As shown in the picture, this is a case in the front-end advanced classic book [Sharp jquery]. Use the attr method to add attributes to elements to achieve selection. with cancel effect.
Requirements: 1. Click Select All/Select All to change the selected status of the four check boxes below;
2. Click the button below individually, as long as there are unselected ones, the top onesSelect all/unselect all is in the unselected state. If all are selected, the select all/unselect all above will also automatically become selected.
<script>"#checkedAll").on("click",
// 判断点击后this.checked的结果,默认未选中即为false,第一次点击则为true,第二次为false,再赋值给下面的input(此处逻辑与书上稍有不同) // 注意事项: 使用attr给表单元素设置选中状态时,第二个参数一定要是布尔值true/false,不能习惯性写成带引号,那就是字符串了。
if(this.checked){ $("input[name=items]").attr("checked",true); }else{ $("input[name=items]").attr("checked",false); } })</script>
It seems to run fine, but after clicking multiple times, you will find that the attributes can be added, but the selected The status has not changed.
what's wrong?
This is due to the version of jQuery. After 1.6, for the inherent attributes of elements, you should use <strong>prop()</strong> method.
<script>$("#checkedAll").on("click",function(){ console.log(!this.checked);if(this.checked){ $("input[name=items]").prop("checked",true); }else{ $("input[name=items]").prop("checked",false); } })</script>
The above code can also be simplified to
<script>$("#checkedAll").on("click",function(){ $("input").prop("checked",this.checked); })</script>
The above is the detailed content of Problems when jquery attr handles form elements such as checkbox / select. For more information, please follow other related articles on the PHP Chinese website!