0

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.

0

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

if there are already some unchecked check boxes are available, So its getting all the unchecked checkboxes value with current unchecked checkbox value, But Here I want only one unchecked checkbox value which is currently unchecked.
@kiranstack so your script is in a change event handler
Yes, its in onclick event.
0

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();

Working Demo

3 Comments

use var with arrchecked and arrunchecked
this will return arrays with true and false values... I don't think that is what OP is after
Updated the answer with fiddle.
0

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.

3 Comments

if there are already some unchecked check boxes are available, So its getting all the unchecked checkboxes value with current unchecked checkbox value, But Here I want only one unchecked checkbox value which is currently unchecked.
@kiranstack you can place a trigger at the closing like in the code:}).change();.
still its not able to get the current uncheched checkbox value..instead its getting all the unchecked checkbox values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.