2011-06-27 45 views
2

所以我有2类复选框。获取复选框值与JS

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

什么是通过共享相同的名称/班看看,如果他们被检查,如果这样的价值添加到字符串的所有复选框进行搜索的最佳途径?

+0

看到http://stackoverflow.com/questions/416752/select-values-of-checkbox-group-with-jquery – Fortega

回答

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

+0

你是男人。感谢所有人。非常感激。 – endy

1
+0

我已经看过,但我无法获得我生命中的价值清单。 – endy

+0

'$('input:checked [name = foo]')。val()'会给你检查当前值为“foo” – jerluc

1

给您复选框共同类,然后:

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

或者更直接

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

获取所有选中的复选框:

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

获取所有复选框:

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

他真的想要得到它们吗? – Giann

+0

并不是真的,但是我已经添加了全屏查看功能,以防万一他希望使用所有复选框值操纵他站点中的进一步过程。 –

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