2011-06-27 44 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(","); 
}