Today, when creating a project function, you need to display the checkbox option for the user to choose. Because the front-end is not very skilled, a simple Demo is made, and some minor problems are encountered, I want to help students who encounter similar problems. obtain the selected items of the checkbox.
2. Select All checkbox options.
The checkbox code segment used for testing:
The Code is as follows:
Grade 1
Grade 2
Grade 3
Grade 4
Fifth grade
Grade 6
Grade 7
Eighth grade
1. First, obtain the checkbox selected items. Most of the methods found on the Internet are obtained using each:
The Code is as follows:
$ ("Input [name = 'checkbox'] [checked]"). each (function (){
Alert (this. value );
})
However, I encountered a problem during the test. This method can be obtained in IE, but the selected items cannot be obtained in firefox and chrome. The test result is as follows:
Test results in IE (I use IE10 ):
Effects of IE10:
Effect of chrome:
Search on google to find the cause:
URL: the number of input checkboxes selected by Jquery. IE is normal, and FF and Chrome cannot get the value.
Because the jquery version I used is 1.7.2, I need to use: checked to obtain it. The modified code:
The Code is as follows:
// Obtain the selected item
$ ('# Huoqu2'). click (function (){
Certificate ('{show'{.html ("");
$ ("Input [name = 'abc']: checked"). each (function (){
// Alert (this. value );
$ ('# Show'). append (this. value + "");
});
});
Effect in chrome:
Ii. Select all checked items in the checkbox:
Since the two are relatively simple, I will directly go to the Code:
The Code is as follows:
// Select all/cancel all
$ ('# Quanxuan'). toggle (function (){
$ ("Input [name = 'abc']"). attr ("checked", 'true ');
}, Function (){
$ ("Input [name = 'abc']"). removeAttr ("checked ");
});
// Invert Selection
$ ('# Fanxuan'). click (function (){
$ ("Input [name = 'abc']"). each (function (){
If ($ (this). attr ("checked ")){
$ (This). removeAttr ("checked ");
} Else {
$ (This). attr ("checked", 'true ');
}
});
});
Summary:
When jquery is earlier than 1.3, the following operations are performed to obtain the selected items of the checkbox:
The Code is as follows:
$ ("Input [name = 'abc'] [checked]"). each (function (){
Alert (this. value );
});
When jquery is later than 1.3, the following operations are performed to obtain the selected items of the checkbox:
The Code is as follows:
$ ("Input [name = 'abc']: checked"). each (function (){
Alert (this. value );
});
Complete Test Demo code is provided:
The Code is as follows: