开发者

Get check box values with JS

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?


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


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
   }
});


jQuery :checked selector to the rescue.


Give your checkboxes a common class, then:

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

Or more directly

$('.classofcheckbox:checked').each(function() {
   // do stuff...
});


function checkedBoxesToString(name) {
    var checked = [];
    $('[name=' + name + ']:checked').each(function (a, b) {
        checked.push($(b).val());
    });
    return checked.join(",");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜