SkyeBoniwell
SkyeBoniwell

Reputation: 7092

getting a list of checkbox Ids

I'm trying to get a string of IDs for a group of checkboxes. The code below does contain the IDs, but it also contains blank spaces and double commas for checkboxes that are not checked.

Is there a way to get a string of just the IDs?

Thanks!

$($('input[type=checkbox][name=selector]')).each(function () {
       var sThisVal = (this.checked ? this.id : "");
       sList += (sList == "" ? sThisVal : "," + sThisVal);
});

Upvotes: 0

Views: 43

Answers (1)

Adil
Adil

Reputation: 148110

You can use map() to get comma separated ids of checked checkboxes

strIds = $('input[type=checkbox][name=selector]').map(function () {                        
      if(this.checked) return  this.id;    
}).get().join(',');

Making it little simple by simplifying selector and making selector to return on checked checkboxes using :checked selector.

strIds = $('[name=selector]:checked').map(function () {                        
       return  this.id;    
}).get().join(',');

Upvotes: 5

Related Questions