Home > Web Front-end > JS Tutorial > body text

Problems when jquery attr handles form elements such as checkbox / select

巴扎黑
Release: 2017-06-26 14:23:26
Original
1477 people have browsed it

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>
Copy after login

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",
Copy after login
        // 判断点击后this.checked的结果,默认未选中即为false,第一次点击则为true,第二次为false,再赋值给下面的input(此处逻辑与书上稍有不同)
        // 注意事项: 使用attr给表单元素设置选中状态时,第二个参数一定要是布尔值true/false,不能习惯性写成带引号,那就是字符串了。
Copy after login
        if(this.checked){
            $("input[name=items]").attr("checked",true); 
        }else{
            $("input[name=items]").attr("checked",false);
        }
    })</script>
Copy after login

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>
Copy after login

The above code can also be simplified to

<script>$("#checkedAll").on("click",function(){
        $("input").prop("checked",this.checked);
    })</script>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template