我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
当前回答
$("input[name='<your_name_of_selected_group_checkboxes>']:checked").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');
}
});
});
如果你需要以数组的形式获取所有选中复选框的值:
let myArray = (function() {
let a = [];
$(".checkboxes:checked").each(function() {
a.push(this.value);
});
return a;
})()
你可以这样使用: 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的值。
如果只有复选框具有给定的类名,则不需要指定:checkbox筛选器。
const newArray = $('.yourClass:checked').map(function(){return $(this).val()}).get();
console.log(newArray);
$('input.theclass[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});