我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
当前回答
你可以这样使用: HTML:
<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>
JQuery:
$(".yourClass:checkbox").filter(":checked")
它将选择1和3的值。
其他回答
HTML
<p> <input type="checkbox" name="fruits" id="fruits" value="1" /> Apple </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="2" /> Banana </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="3" /> Mango </p>
<p> <input type="checkbox" name="fruits" id="fruits" value="4" /> Grape </p>
Jquery
用于存储选定的水果值定义数组。
fruitArray = [];
美元。每个将迭代选中的复选框并推入数组。
$.each($("input[name='fruits']:checked"), function (K, V) {
fruitArray.push(V.value);
});
一个通过类名获取选中复选框id的简单方法:
$(".yourClassName:checkbox:checked").each(function() {
console.log($(this).attr("id"));
});
我知道这个问题已经有了很多很好的答案,但我在浏览时发现了这个,我发现它真的很容易使用。我想分享给其他想看的人。
HTML:
<fieldset>
<!-- these will be affected by check all -->
<div><input type="checkbox" class="checkall"> Check all</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
<!-- these won't be affected by check all; different field set -->
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
jQuery:
$(function () {
$('.checkall').on('click', function () {
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
});
});
参考: 最简单的“检查所有”与jQuery
$('input.yourClass:checkbox:checked').each(function () {
var sThisVal = $(this).val();
});
这将获得类名为“yourClass”的所有复选框。我喜欢这个例子,因为它使用jQuery选择器检查,而不是做条件检查。就我个人而言,我也会使用数组来存储值,然后根据需要使用它们,比如:
var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
arr.push($(this).val());
});
你可以这样使用: HTML:
<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>
JQuery:
$(".yourClass:checkbox").filter(":checked")
它将选择1和3的值。