使用 jQuery 获取选定复选框的值

IT技术 javascript jquery
2021-02-25 04:13:33

我想遍历复选框组“locationthemes”并构建一个包含所有选定值的字符串。So when checkbox 2 and 4 are selected the result would be: "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/但没有示例如何按名称选择复选框组。

我怎样才能做到这一点?

6个回答

在 jQuery 中,只需使用一个属性选择器,如

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

选择名称为“locationthemes”的所有选中的输入

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

//or

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

演示


VanillaJS 中

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

演示


在 ES6/spread 运算符中

[...document.querySelectorAll('input[name="locationthemes"]:checked')]
   .forEach((cb) => console.log(cb.value));

演示

你,我的朋友,是救命稻草。
2021-05-04 04:13:33
特别是我喜欢使用控制台日志的想法。感谢那。
2021-05-05 04:13:33
$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

工作演示

或者

使用jQuery的is()功能:

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

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

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

将作为数组返回值,如:

array => [2,3]

假设城堡和谷仓被检查,其他人没有。

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

这应该是评论
2021-05-04 04:13:33

使用jquery的map功能

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});
理解 checkboxName 在这个例子中应该是“locationthemes”
2021-05-11 04:13:33