使用jQuery获取所选复选框的值 [英] use jQuery to get values of selected checkboxes
本文介绍了使用jQuery获取所选复选框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历checkboxgroup'locationthemes'并构建一个包含所有选定值的字符串。
因此,当选中复选框2和4时,结果将是:3,8
I want to loop through the checkboxgroup 'locationthemes' and build a string with all selected values. 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/ 但没有示例如何按名称选择复选框组。
I checked here: http://api.jquery.com/checked-selector/ but there's no example how to select a checkboxgroup by its name.
我怎么能这样做?
推荐答案
在jQuery中只需使用属性选择器,如
In jQuery just use an attribute selector like
$('input[name="locationthemes"]:checked');
选择所有选中的输入,名称为locationthemes
to select all checked inputs with name "locationthemes"
console.log($('input[name="locationthemes"]:checked').serialize());
//or
$('input[name="locationthemes"]:checked').each(function() {
console.log(this.value);
});
In VanillaJS
[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
console.log(cb.value);
});
In ES6 /差价运算符
In ES6/spread operator
[...document.querySelectorAll('input[name="locationthemes"]:checked')]
.forEach((cb) => console.log(cb.value));
这篇关于使用jQuery获取所选复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文