28

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.

jayAnn
  • 827
  • 3
  • 18
  • 38

4 Answers4

52
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/

James Montagne
  • 77,516
  • 14
  • 110
  • 130
31

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/

Mo Valipour
  • 13,286
  • 12
  • 61
  • 87
  • what is the requirement of get() function call here, it seems $(":checkbox:checked").map(idSelector) could do the job itself? – TechnicalSmile Jan 16 '16 at 15:29
  • 1
    `.get()` converts a jquery array to a native array. I guess you could live without it too. -- you can testify the difference by calling a jquery function (e.g. `.find()`) on the outcome and you can see the difference – Mo Valipour Jan 16 '16 at 17:44
5

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;
});
John Kalberer
  • 5,690
  • 1
  • 23
  • 27
2

This can be done using .map, though in this case it is not really different from using .each:

$(":checkbox").change(function() {
    var notChecked = [], checked = [];
    $(":checkbox").map(function() {
        this.checked ? checked.push(this.id) : notChecked.push(this.id);
    });
    alert("checked: " + checked);
    alert("not checked: " + notChecked);
});

You can test it here.

karim79
  • 339,989
  • 67
  • 413
  • 406