Using jquery to get all checked checkboxes with a

2019-01-08 05:04发布

I know I can get all checked checkboxes on a page using this:

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

But I am now using this on a page that has some other checkboxes that I don't want to include. How would I change the above code to only look at checked checkboxes that have a certain class on them?

12条回答
该账号已被封号
2楼-- · 2019-01-08 05:21
$('input:checkbox.class').each(function () {
       var sThisVal = (this.checked ? $(this).val() : "");
  });

An example to demonstrate.

:checkbox is a selector for checkboxes (in fact, you could omit the input part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions). .class is the selector for element class attribute containing class.

查看更多
走好不送
3楼-- · 2019-01-08 05:22
 $('input.theclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : "");
 });
查看更多
我命由我不由天
4楼-- · 2019-01-08 05:26
$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});
查看更多
太酷不给撩
5楼-- · 2019-01-08 05:30

Obligatory .map example:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;
}).get();
alert(checkedVals.join(","));
查看更多
等我变得足够好
6楼-- · 2019-01-08 05:31

Simple way to get all of values into an array

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

})();

console.log(valores);
查看更多
Emotional °昔
7楼-- · 2019-01-08 05:33
 $('input.myclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : ""); });

See jQuery class selectors.

查看更多
登录 后发表回答