Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY: get the id's of the checked and not checked checkBox

I have this not so many checkboxes:

<input type="checkbox" id="mango" value="mango" /> <label>MANGO</label><br>
<input type="checkbox" id="santol" value="santol" /> <label>SANTOL</label><br>
<input type="checkbox" id="guava" value="guava" /> <label>GUAVA</label><br>
<input type="checkbox" id="lomboy" value="lomboy" /> <label>LOMBOY</label><br>
<input type="checkbox" id="apple" value="apple" /> <label>APPLE</label><br>
<input type="checkbox" id="orange" value="orange" /> <label>ORANGE</label><br>
 ...................<>

Now, what I'm trying to do is get all the ID's of check boxes with check, and no check and put in an array. Something like this:

"fruitsGranted":["apple","lomboy","orange"]; //check is true
"fruitsDenied":["mango","santol","guava"];  //check false

can please someone show me how to do it.? thanks.

like image 220
jayAnn Avatar asked Aug 01 '11 16:08

jayAnn


3 Answers

var someObj={};
someObj.fruitsGranted=[];
someObj.fruitsDenied=[];

$("input:checkbox").each(function(){
    var $this = $(this);

    if($this.is(":checked")){
        someObj.fruitsGranted.push($this.attr("id"));
    }else{
        someObj.fruitsDenied.push($this.attr("id"));
    }
});

http://jsfiddle.net/UqrYJ/

like image 192
James Montagne Avatar answered Nov 10 '22 23:11

James Montagne


I think I got a shorter version here:

var idSelector = function() { return this.id; };
var fruitsGranted = $(":checkbox:checked").map(idSelector).get();
var fruitsDenied = $(":checkbox:not(:checked)").map(idSelector).get();

You can see it in action here: http://jsfiddle.net/XPMjK/3/

like image 36
Mo Valipour Avatar answered Nov 11 '22 00:11

Mo Valipour


I would do this something like this:

var all, checked, notChecked;
all = $("input:checkbox");
checked = all.filter(":checked");
notChecked = all.not(":checked)");

After that you can use jQuery.map to get the ids of each collection.

var checkedIds = checked.map(function() {
    return this.id;
});

var notCheckedIds = notChecked.map(function() {
    return this.id;
});
like image 5
John Kalberer Avatar answered Nov 10 '22 23:11

John Kalberer