Forms are often encountered in front-end development, and the checkbox check box is also indispensable. There are three operations for the check box: select all, select none, and select inverse. The following is an analysis of zero degree.
I. Select all checkpoints
As we all know, the method of selecting checkbox is to add the attribute checked: 'checked' to it, so we can use jquery to write it like this:
The code is as follows: |
Copy code |
$ ('Input [type = button] '). click (function (){ $ ('Input [type = checkbox] '). attr ('checked', 'checked '); }) |
In this way, clicking the button is a select-all operation, but you do not know it. Adding attributes like checkbox is not recommended by w3c. Please refer to the recommendations on her official website, the property value of checked is a Boolean value. Therefore, the property checked of checkbox should be set to true. The code is as follows:
The code is as follows: |
Copy code |
$ ('Input [type = button] '). click (function () {$ ('input [type = checkbox]'). attr ('checked', true ); }) |
II. All checkboxes are not selected
If you select all, the opposite is true if you do not select All. You can write as follows:
The code is as follows: |
Copy code |
$ ('Input [type = button] '). click (function (){ $ ('Input [type = checkbox] '). removeattr ('checked '); }) |
Similarly, you 'd better write it like this:
The code is as follows: |
Copy code |
$ ('Input [type = button] '). click (function () {$ ('input [type = checkbox] '). attr ('checked', false );}) |
III. checkbox invert selection
The logic of the inverse selection is to change the selected status to the unselected status and the unselected status to the selected status. We can know from the above that the checked value is a Boolean value, in this way, we can take it for judgment, so the code can be written:
The code is as follows: |
Copy code |
$ ('Input [type = button] '). click (function (){ $ ('Input [type = checkbox] '). attr ('checked ',! $ (This). attr ('checked ')); }) |
In this way, the goal can be achieved. However, the above functions may not be implemented in jquery 1.10.x. In this case, you need to load jquery of another version, this should be a small bug in jquery. You can test it.
Supplement: earlier jquery libraries support attr ("checked") = "checked", but not attr ("checked") = true.
Therefore, the compatible code used to check whether the checkbox is selected is as follows:
The code is as follows: |
Copy code |
If ($ ("# dependencies "). attr ("checked") = "checked" | $ ("# checked "). attr ("checked") = true ){ Alert ('selected '); } Else { Alert ('unselect '); } |