我知道我可以得到所有选中的复选框在页面上使用这个:

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?


当前回答

$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

这将获得类名为“yourClass”的所有复选框。我喜欢这个例子,因为它使用jQuery选择器检查,而不是做条件检查。就我个人而言,我也会使用数组来存储值,然后根据需要使用它们,比如:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});

其他回答

 $('input.theclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : "");
 });

获取所有值到数组的简单方法

var valores = (function () {
    var valor = [];
    $('input.className[type=checkbox]').each(function () {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);

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);        
});

                                       
<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

强制的。map示例:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;
}).get();
alert(checkedVals.join(","));