使用JS获取复选框值

时间:2011-06-27 07:36:41

标签: javascript jquery html

所以我有两类复选框。

  <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" />

当选中一个框时,我想运行一个jQuery函数,它将分配两个变量

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

因此,假设只在foo组中选中了第一个复选框,其中两个都在条形图组中被选中。组值如下

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

搜索共享相同名称/类的所有复选框的最佳方法是查看它们是否已被选中,如果是,请将它们的值添加到字符串中?

5 个答案:

答案 0 :(得分:2)

获取所有选中的复选框:

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

获取所有复选框:

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

答案 1 :(得分:2)

您可以尝试类似

的内容
 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(',');

查看working demo

答案 2 :(得分:1)

答案 3 :(得分:1)

给你的复选框一个公共类,然后:

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

或更直接

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

答案 4 :(得分:1)

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