2012-07-02 58 views
55

我想遍历复选框组'locationthemes'并构建一个包含所有选定值的字符串。当复选框2和4被选为 那么结果将是:“3,8”使用jQuery获取所选复选框的值

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" /> 
<label for="checkbox-1">Castle</label> 
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" /> 
<label for="checkbox-2">Barn</label> 
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" /> 
<label for="checkbox-3">Restaurant</label> 
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" /> 
<label for="checkbox-4">Bar</label> 

我曾经到过这里:http://api.jquery.com/checked-selector/但有没有例子,如何选择由它的名字checkboxgroup。

我该怎么做?

回答

125

在jQuery中只需使用一个属性选择像

$('input[name="locationthemes"]:checked'); 

选择名称为 “locationthemes” 所有检查输入

console.log($('input[name="locationthemes"]:checked').serialize()); 

//or 

$('input[name="locationthemes"]:checked').each(function() { 
    console.log(this.value); 
}); 

Demo


VanillaJS

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) { 
    console.log(cb.value); 
}); 

Demo

+4

你,我的朋友,是一个拯救生命的人。 – Haring10

+0

尤其我喜欢使用控制台日志的想法。感谢那。 –

24
$('input:checkbox[name=locationthemes]:checked').each(function() 
{ 
    // add $(this).val() to your array 
}); 

工作Demo

OR

使用jQuery的is()功能:

$('input:checkbox[name=locationthemes]').each(function() 
{  
    if($(this).is(':checked')) 
     alert($(this).val()); 
}); 

4
You can also use the below code 
$("input:checkbox:checked").map(function() 
{ 
return $(this).val(); 
}).get(); 
+1

如何将此结果分配到变量 –

10

使用jQuery的map功能

var checkboxValues = []; 
$('input[name=checkboxName]:checked').map(function() { 
      checkboxValues.push($(this).val()); 
}); 
+0

中,同时了解在此示例中checkboxName应该是“locationthemes” – hrabinowitz

1

因此,所有在同一行:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); }).get().join(","); 

..A注意有关选择[id*="checkbox"],它会抓住任何物品字符串“复选框”在其中。这里有点笨拙,但如果你想从.NET CheckBoxList之类的东西中拉出选定的值,这真的很好。在这种情况下,“复选框”就是您给CheckBoxList控件的名称。

6

映射数组是最快和最干净的。

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; }) 

将返回值作为像的数组:

array => [2,3] 

假设城堡和谷仓进行了检查,其他则不是。

6

$("#locationthemes").prop("checked")

+0

这应该是一个注释 –