2

So i have 2 categories of checkboxes.

  <input type="checkbox" name="foo"  value="val1" />
  <input type="checkbox" name="foo"  value="val2" />


  <input type="checkbox" name="bar"  value="val1" />
  <input type="checkbox" name="bar"  value="val2" />

When a box is checked I want to run a jQuery function that will assign two variables

  var foo = //the values of the checked boxes with the foo name
  var bar = //the values of the checked boxes with the bar name

So lets say only the first check box was checked in the foo group where as both were checked in the bar group. The groups values would be as follows

 var foo = val1;
 var bar = val1,val2;

What is the best way to search through all checkboxes that share the same name/class Look to see if they are checked and if so add their value to a string?

endy
  • 3,872
  • 5
  • 29
  • 43

5 Answers5

2

Get all checked checkboxes :

$(':checkbox').is(':checked').each(function() {
   if ($(this).value) {
     //get values here
   }
});

Get all checkboxes :

$(':checkbox').each(function() {
   if ($(this).value) {
     //get values here
   }
});
Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72
2

You can try something like

 var foo = $("input:checkbox[name='foo']:checked").map(function(){
                            return this.value;
                        }).get().join(',');

 var bar = $("input:checkbox[name='bar']:checked").map(function(){
                            return this.value;
                        }).get().join(',');

See a working demo

rahul
  • 184,426
  • 49
  • 232
  • 263
1

jQuery :checked selector to the rescue.

jerluc
  • 4,186
  • 2
  • 25
  • 44
1

Give your checkboxes a common class, then:

$('.classofcheckbox').each(function() {
   if ($(this).val()) {
     // do stuff...
   }
});

Or more directly

$('.classofcheckbox:checked').each(function() {
   // do stuff...
});
Giann
  • 3,142
  • 3
  • 23
  • 33
1
function checkedBoxesToString(name) {
    var checked = [];
    $('[name=' + name + ']:checked').each(function (a, b) {
        checked.push($(b).val());
    });
    return checked.join(",");
}
Bemmu
  • 17,849
  • 16
  • 76
  • 93