我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
我知道我可以得到所有选中的复选框在页面上使用这个:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?
当前回答
一个通过类名获取选中复选框id的简单方法:
$(".yourClassName:checkbox:checked").each(function() {
console.log($(this).attr("id"));
});
其他回答
<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />
<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("#demo").live("click", function () {
$("input:checkbox[class=chk]:checked").each(function () {
alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
});
});
</script>
http://www.jqueryfaqs.com/Articles/Get-values-of-all-checked-checkboxes-by-class-name-using-jQuery.aspx
$('. class:checkbox:checked')将为您提供类class中所有选中的复选框。
$(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');
}
});
});
如果只有复选框具有给定的类名,则不需要指定:checkbox筛选器。
const newArray = $('.yourClass:checked').map(function(){return $(this).val()}).get();
console.log(newArray);
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
一个要演示的例子。
:checkbox是复选框的选择器(事实上,你可以省略选择器的输入部分,尽管我发现在库的早期版本中,你会得到奇怪的结果。我相信它们在后来的版本中得到了修复)。 .class是包含class的元素class属性的选择器。