简体   繁体   English

返回:使用is()选中的复选框的值

[英]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: 然后在代码的某处,我想将每个set:checked值放入数组中:

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'. 但是什么也没返回,我也调试了一下,在控制台上它说对象没有方法“ each”。 I tried using not(':checked') and it is working okay, it returned the unchecked values. 我尝试使用not(':checked'),并且工作正常,它返回了未经检查的值。

Use .map() to create array 使用.map()创建数组

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

.filter() 。过滤()

.is() returns a Boolean value. .is()返回一个布尔值。

You need to use .filter() 您需要使用.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') . 使用filter(':checked')

not() is not the opposite of is() , but it's !.is() . not()不是is()的反义词,而是!.is() On the other hand filter() is the opposite of not() . 另一方面, filter()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 : is()检查当前元素集中的一个元素是否与选择器匹配,并返回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. not()是一种过滤方法,它使用选择器检查每个元素,并仅返回与选择器不匹配的元素。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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