简体   繁体   中英

Return :checked checkboxes value with is()

I have sets of checkboxes so I assigned each set in a variable.

var $set1 = $('.suppliers'), $set2 = $('.products'), $set3 = $('.customer')//etc...

Then somewhere on my code, I want to put each set :checked values in an array:

var set1Arr = [];

$set1.is(':checked').each(function() {
   set1Arr.push($(this).val());
});

But nothing is returned, I also debugged and on console it says Object has no method 'each'. I tried using not(':checked') and it is working okay, it returned the unchecked values.

Use .map() to create array

var set1Arr = $set1.filter(':checked').map(function() {
   return this.value;
}).get();

.filter()

.is() returns a Boolean value.

You need to use .filter()

var set1Arr = [];
$set1.filter(':checked').each(function() {
   set1Arr.push($(this).val());
});

or better

var set1Arr =  $set1.filter(':checked').map(function() {
   return this.value
}).get();

Use filter(':checked') .

not() is not the opposite of is() , but it's !.is() . On the other hand filter() is the opposite of not() .


You just misunderstood how both methods work.

is() checks if one element in the current set of elements matches the selector, and returns a boolean :

if($('input[type="checkbox"]').is(':checked')){
    //if at least one checkbox is checked do something...
}

not() is a filtering method, it checks each element with the selector and returns only those that do not match the selector.

Try like

$set1.each(function() {
    if($(this).is(':checked'))
        set1Arr.push($(this).val());
});
$set1.each(function() {
   if($(this).is(':checked')){
       set1Arr.push($(this).val());
   }
});

Try this:

var checkboxValue = $(this).prop('checked');

or

$(this).is(':checked'); //return boolean 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM