views:

74

answers:

5

I have a simle html div with a variable number of input checkboxes and i whould like to chek which chekbox is cheked and which isn't

HTML code:

<div>
    <input type="checkbox" val="1"/>Check One<br/>
    <input type="checkbox" val="2" checked="checked"/>Check Two<br/>
</div>

Javascript code:

var $kids = $("div").children("input");

for (var i = 0; i < $kids.length; i ++) {
    // if i alert($kids[i]); i get [object HTMLInputElement] how can i work with it?
    alert ($kids[i].val()); // doesn't work
}

In jQuery site i read children() method can "Get a set of elements containing all of the unique immediate children of each of the matched set of elements." but what is a "set of elements"and how can I work with it?

+1  A: 

EDIT:

I should have read your question more carefully you were asking how to iterate over the the set. as has already been stated you can do:

$('div input:checked').each(function(){
   // do something with the item this is always the current element in the iteration
});

or

$.each(yourVar, function(i, e){
   // your var can be anything iterable really... an object, an array i is the index and e is the value for that index
});

$('div input:checked'); should work.

prodigitalson
A: 

Working with a set of elements is very similar to working with a single element in jQuery.. There are a lot of methods you can use to split the segments up .each() allows you to work with each matched element, .css(), .animate(), .show() etc all work with all the elements matched in the set as well. You can used .get() or just an array index [0] to get single elements out of the jQuery matched set.

gnarf
+3  A: 

$("input:checkbox:checked") or $("input:checkbox:not(:checked)")

You should add an id to your container to limit the options...
<div id="container"> inputs here </div>

Then you can use...
var checked = $("#container input:checkbox:checked");
var unchecked = $("#container input:checkbox:not(:checked)");

Tracker1
A: 
  • This selector will get you all the checkboxes: input:checkbox
  • This selector will get you all the checkboxes that are checked: input:checkbox:checked
  • This selector will get you all the checkboxes that are not checked: input:checkbox:not(:checked)
Dominic Barnes
A: 

You can access the elements with $kids[i], but what you're getting back isn't a JQuery object, it's a standard DOM element. Therefore you can't call the .val() method, because that doesn't exist for DOM objects.

So really you only have to make a small modification:

var $kids = $("div").children("input");

for (var i = 0; i < $kids.length; i ++) {
    // if i alert($kids[i]); i get [object HTMLInputElement] how can i work with it?
    alert ($kids[i].checked); // does work :-)
}

Hope this helps!

Jieren