我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
当前回答
$(document).ready(function(){
$('input.checkD[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$(this).val('true');
}
else if($(this).prop("checked") == false){
$(this).val('false');
}
});
});
其他回答
我不确定它是否对您的特定情况有帮助,我也不确定在您的情况下,您想要包含的复选框是否都是单个表单或div或表的一部分,但您总是可以选择特定元素中的所有复选框。例如:
<ul id="selective">
<li><input type="checkbox" value="..." /></li>
<li><input type="checkbox" value="..." /></li>
<li><input type="checkbox" value="..." /></li>
<li><input type="checkbox" value="..." /></li>
</ul>
然后,使用下面的jQuery,它只通过id="selective"的UL内的复选框:
$('#selective input:checkbox').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
$('input.myclass[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : ""); });
请参阅jQuery类选择器。
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
一个要演示的例子。
:checkbox是复选框的选择器(事实上,你可以省略选择器的输入部分,尽管我发现在库的早期版本中,你会得到奇怪的结果。我相信它们在后来的版本中得到了修复)。 .class是包含class的元素class属性的选择器。
你可以这样试试
let values = (function() {
let a = [];
$(".chkboxes:checked").each(function() {
a.push($(this).val());
});
return a;
})();
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);
});