Flo*_*Flo 72 javascript jquery
我想遍历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>
Run Code Online (Sandbox Code Playgroud)
我在这里查了一下:http://api.jquery.com/checked-selector/但是没有例子如何按名称选择复选框组.
我怎样才能做到这一点?
fca*_*ran 155
在jQuery中只需使用属性选择器
$('input[name="locationthemes"]:checked');
Run Code Online (Sandbox Code Playgroud)
选择名称为"locationthemes"的所有选中输入
console.log($('input[name="locationthemes"]:checked').serialize());
//or
$('input[name="locationthemes"]:checked').each(function() {
console.log(this.value);
});
Run Code Online (Sandbox Code Playgroud)
在VanillaJS
[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
console.log(cb.value);
});
Run Code Online (Sandbox Code Playgroud)
在ES6 /传播运营商
[...document.querySelectorAll('input[name="locationthemes"]:checked')]
.forEach((cb) => console.log(cb.value));
Run Code Online (Sandbox Code Playgroud)
Tal*_*lha 30
$('input:checkbox[name=locationthemes]:checked').each(function()
{
// add $(this).val() to your array
});
Run Code Online (Sandbox Code Playgroud)
工作演示
要么
使用jQuery的is()功能:
$('input:checkbox[name=locationthemes]').each(function()
{
if($(this).is(':checked'))
alert($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
Ste*_*rry 14
映射数组是最快最干净的.
var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })
Run Code Online (Sandbox Code Playgroud)
将返回值作为数组,如:
array => [2,3]
Run Code Online (Sandbox Code Playgroud)
假设城堡和谷仓被检查,其他人没有.
May*_*lor 12
使用jquery的map功能
var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
checkboxValues.push($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
更现代的方式来做到这一点:
const selectedValues = $('input[name="locationthemes"]:checked').map( function () {
return $(this).val();
})
.get()
.join(', ');
Run Code Online (Sandbox Code Playgroud)
我们首先找到所有具有给定名称的选定复选框,然后 jQuery 的 map() 遍历每个复选框,调用其回调以获取值,并将结果作为新的 jQuery 集合返回,该集合现在保存复选框值。然后我们调用 get() 来获取值数组,然后 join() 将它们连接成一个字符串 - 然后将其分配给常量 selectedValues。
小智 6
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
SlectedList.push($(this).val());
});
Run Code Online (Sandbox Code Playgroud)
小智 5
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
306165 次 |
| 最近记录: |