Tom Westfall
Tom Westfall

Reputation: 27

List of checkboxes checked for specific classes

I would like to get a list of names of which checkboxes are checked in a specific DIV (page-wrap). I am creating a filter of sorts and have a treeview of different types like color, quality, grain, etc... Each has its own class assigned to them. Color has a class of color_cb, Quality is product_cb, Grain is grain_cb. The following code works great for any one of them but I'd like to test for all 3. Is there a way to modify this for all 3.

var selected = [];
    $('#page-wrap input:checkbox.color_cb:checked').each(function() {
        selected.push($(this).attr('name'));
    });
alert(selected.join(","));

I've tried this but it doesn't work.

var selected = [];
    $('#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked').each(function() {
        selected.push($(this).attr('name'));
    });
alert(selected.join(","));

Upvotes: 0

Views: 51

Answers (3)

Balachandran
Balachandran

Reputation: 9637

use comma separator b/w selected element

$('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked')
                                             ^^^^-- add , seperator    

or use map()

var selected = $('#page-wrap input:checkbox.color_cb:checked ,#page-wrap input:checkbox.product_cb:checked').map(function () {
     return $(this).attr('name');
 }).get();

Upvotes: 1

Håkon Egset Harnes
Håkon Egset Harnes

Reputation: 15107

Simply removing the class should work fine.

var selected = [];
$('#page-wrap input:checkbox:checked').each(function() {
    selected.push($(this).attr('name'));
});
alert(selected.join(","));

http://jsfiddle.net/60hnvnh9/1/

If there are checkboxes that you want to avoid targeting, simply give the checkboxes another, common class, and target that.

Upvotes: 0

jeronimo vallelunga
jeronimo vallelunga

Reputation: 204

'#page-wrap input:checkbox.color_cb:checked input:checkbox.product_cb:checked'

this query selector means that input:checkbox.product_cb:checked is child of input:checkbox.color_cb:checked

But, i think you are looking for elements that accomplish one OR the other query, for that you have to use a comma separator, like this:

'#page-wrap input:checkbox.color_cb:checked, #page-wrap input:checkbox.product_cb:checked'

Upvotes: 0

Related Questions