我想遍历checkboxgroup 'locationthemes‘,并使用所有选定的值构建一个字符串。因此,当选中复选框2和4时,结果将是:"3,8“
<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。
我该怎么做呢?
发布于 2012-07-02 19:30:59
在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
在ES6中/扩展运算符
[...document.querySelectorAll('input[name="locationthemes"]:checked')]
.forEach((cb) => console.log(cb.value));Demo
发布于 2012-07-02 19:33:24
$('input:checkbox[name=locationthemes]:checked').each(function()
{
// add $(this).val() to your array
});工作Demo
或
使用jQuery的is()函数:
$('input:checkbox[name=locationthemes]').each(function()
{
if($(this).is(':checked'))
alert($(this).val());
});
发布于 2016-03-04 03:08:35
Map数组是最快、最干净的。
var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })将返回值作为数组,如下所示:
array => [2,3]假设城堡和谷仓都被检查过了而其他人没有。
https://stackoverflow.com/questions/11292778
复制相似问题