简体   繁体   English

循环时如何忽略禁用的复选框值

[英]How to ignore disabled checkbox values while looping

below is my code: 下面是我的代码:

Cell.setAttribute('type', 'checkbox');
Cell.setAttribute('name', "Size");

based on condition I will set some values to 'checked' and 'disabled'. 根据条件,我会将一些值设置为“选中”和“禁用”。

Cell.setAttribute('checked', 'true');
Cell.setAttribute('disabled', 'true');   

Here 'Size' contains some values which are disabled, both unchecked and checked. 这里的“大小”包含一些禁用的值,包括未选中和已选中。

So whenever I am trying to retrieve the checked values, the default disabled checked boxes are also being returned. 因此,每当我尝试检索检查的值时,也会返回默认的禁用检查框。

I just want the checked values; 我只想要检查的值; not the disabled checked values in SelectedDetails method: 不是SelectedDetails方法中禁用的检查值:

var testCaseArray =[]; 
var checkbox = document.getElementsByName('Size');

for(var i=0; i<checkbox.length; i++){
    if(checkbox[i].checked){ 
        testCaseArray.push(checkbox[i].value);
    }
}

return testCaseArray;

Retrieve all checked checkbox elements in a series, except the disabled one(s), into an Array : 将一系列中所有选中的复选框元素(禁用的元素除外)检索到Array

var chkd = [].slice.call(document.querySelectorAll('input:checked'))
            .filter(function(e) {
               return null == e.getAttribute('disabled');
             });

You can also use this selector to retrieve a Array-like list with the same selection: 您还可以使用此选择器来检索具有相同选择的类似数组的列表:

document.querySelectorAll('input:checked:not(disabled)')

jsFiddle 的jsfiddle

You need to add in the check for disabled, as well as the check for it being checked 您需要添加已禁用的检查以及正在检查的检查

var testCaseArray =[]; 
var checkbox = document.getElementsByName('Size');

for(var i=0; i<checkbox.length; i++){
    if(checkbox[i].disabled){
        continue;
    }
    if(checkbox[i].checked){ 
        testCaseArray.push(checkbox[i].value);
    }
}

return testCaseArray;

Since JavaScript has short-circuit evaluation , just add the condition to your if statement: 由于JavaScript具有短路评估功能 ,因此只需将条件添加到if语句中:

var testCaseArray = [],
    checkbox = document.getElementsByName('Size');

for (var i = 0; i < checkbox.length; ++i) {
    if (!checkbox[i].disabled && checkbox[i].checked) {
        testCaseArray.push(checkbox[i].value);
    }
}

return testCaseArray;

The JavaScript engine will automatically stop evaluating if !checkbox[i].disabled returns false. 如果!checkbox[i].disabled返回false,JavaScript引擎将自动停止评估。

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

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