我想循环判断复选框组"locationthemes",并用所有选定的值构建一个字符串.

<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>

I checked here: http://api.jquery.com/checked-selector/ but there's no example how to select a checkboxgroup by its name.

How can I do this?

推荐答案

In jQuery just use an attribute selector like

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

要 Select 所有名称为"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


In ES6/spread operator

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

Demo

Jquery相关问答推荐

JQuery UI-AutoComplete未显示下拉菜单

使用 Ajax 列出数据(仅显示最后的数据)

Jquery 表数据无法在 html 上正确显示

jQuery:在mousemove事件期间检测按下的鼠标按钮

如何从 onclick div 属性检测 Javascript 中的 control+click?

为什么对同一个 ASP.NET MVC 操作的多个同时 AJAX 调用会导致浏览器阻塞?

如何使用 jQuery 获取所有 ID?

使用 jQuery 和 HTML 导出为 CSV

jQuery从下拉列表中删除一个选项,给定选项的文本/值

Facebook 风格的 JQuery 自动完成插件

如何在我的 WordPress 插件中包含 CSS 和 jQuery?

jQuery ajax 在 asp.net mvc 中上传文件

如何使用 jQuery 停止默认链接点击行为

CSS3 相当于 jQuery slideUp 和 slideDown?

从客户端的对象数组中获取最新日期的优雅方法是什么?

在 jQuery 中 Select 后代元素的最快方法是什么?

使用 jquery 禁用文本框?

删除所有以某个字符串开头的类

如何在 DOM 中移动 iFrame 而不会丢失其状态?

使用 jQuery 将一个标签替换为另一个标签