An jQuery array of all selected checkboxes (per class)

Possible duplicate:
Select checkbox group values ​​using jQuery

In HTML, I have a set of flags grouped together by a class. I want to get an array in jQuery containing all the flags that were selected / checked for this class (so that the other flags on the page are ignored).

So, the HTML looks like this:

<input type="checkbox" class="group1" value="18" checked="checked" /> <input type="checkbox" class="group1" value="20" /> <input type="checkbox" class="group1" value="15" /> <input type="checkbox" class="group2" value="14" /> <input type="checkbox" class="group1" value="55" checked="checked" /> <input type="checkbox" class="group1" value="10" checked="checked" /> <input type="checkbox" class="group2" value="77" checked="checked" /> <input type="checkbox" class="group1" value="11" /> 

Will return the checked / selected group1 flag values ​​to an array like this:

 var values = [ 18, 55, 10 ]; 
+83
javascript jquery html
Jan 20 '10 at 5:05
source share
3 answers

You can use :checkbox and :checked pseudo-selectors and the .class selector, while you make sure that you get the correct elements, only the checked flags with the class you specified.

Then you can easily use the Traversing / map method to get an array of values:

 var values = $('input:checkbox:checked.group1').map(function () { return this.value; }).get(); // ["18", "55", "10"] 
+202
Jan 20 '10 at 5:08
source share

 var matches = []; $(".className:checked").each(function() { matches.push(this.value); }); 
+31
Jan 20 '10 at 5:08
source share

You can also add underscore.js to your project and you can do this in one line:

 _.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()}) 
+5
Jun 10 2018-12-12T00:
source share



All Articles