how to get checked and unchecked check box values in an array using javascript/jquery.
I have a list of check boxes.
Below is the sample code.
<input type="checkbox" class="chkCountry" value="1" checked="checked" />India
<input type="checkbox" class="chkCountry" value="4" checked="checked" />China
<input type="checkbox" class="chkCountry" value="2"/>Pakistan
<input type="checkbox" class="chkCountry" value="3"/>Japan
Here i want to get the checked values in a array unchecked values in another array.
And if again i want to unchecked the checked values(here India and China), i want to get the values(1,4) in another array.
You can use .map() to convert a jQuery object set to an array like
var $checks = $('.chkCountry');
var checked = $checks.filter(':checked').map(function () {
return this.value;
}).get();
var unchecked = $checks.not(':checked').map(function () {
return this.value;
}).get();
To get checked :
arrchecked = $('.chkCountry').map(function() {
if(this.checked)
return this.value;
}).get();
arrunchecked = $('.chkCountry').map(function() {
if(!this.checked)
return this.value;
}).get();
You can use this:
var checked=[], unchecked=[];
$('.chkCountry').change(function() {
if(this.checked){
checked.push(this.value);
unchecked.splice(this.value, 1);
}else{
unchecked.push(this.value);
checked.splice(this.value, 1);
}
}).change();
I stated a .splice()
method to remove element if you need to update the array with uncheck.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.