Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
禁用选项选择javascript_Javascript_Jquery_Underscore.js - Fatal编程技术网

禁用选项选择javascript

禁用选项选择javascript,javascript,jquery,underscore.js,Javascript,Jquery,Underscore.js,我有一个问题,我想启用/显示选项,如果该选项与“ColumnCode”同名且“IsRow”为true。除此之外,该选项处于禁用/隐藏状态 我尝试了下面的代码,但没有成功 var model = { Rows: $('#Rows') }; var columns = [{"ColumnCode":"CollateralType","IsRow":true}, {"ColumnCode":"CollectorUnit","IsRow":true}]; _.each(columns,

我有一个问题,我想启用/显示选项,如果该选项与“ColumnCode”同名且“IsRow”为true。除此之外,该选项处于禁用/隐藏状态

我尝试了下面的代码,但没有成功

var model = {
    Rows: $('#Rows')
};


var columns = 
[{"ColumnCode":"CollateralType","IsRow":true},
{"ColumnCode":"CollectorUnit","IsRow":true}];

_.each(columns, function (col) {
    model.Rows.find('option').each(function () {                       
        if (this.value != col['ColumnCode'] || (this.value == col['ColumnCode'] && !col['IsRow']))
            $(this).attr('disabled', true);
    });
});  
这是选择元素:

<select name="Rows[]" id="Rows">
    <option value="AccountNo">Account No</option>
    <option value="CollateralType">Collateral Type</option>  
</select>

帐号
抵押品类型

有人可以指导吗?

您应该将该循环由内而外,首先遍历选项,然后遍历数组,否则您的选项将不断被重新设置,或者最终可能一直被禁用

您可能还想添加一个类似于
…的默认选项。请选择
值,以确保在禁用所有选项的情况下不会选择任何选项

var model = {
    Rows: $('#Values') // had to change this from #Row for demo to work
};

var columns = [
    {"ColumnCode": "CollateralType", "IsRow": true},  // change this to see different results
    {"ColumnCode": "CollectorUnit",  "IsRow": true}
];

// enable option if option has the same name as "ColumnCode" and "IsRow" is true
model.Rows.find('option').each(function (index, option) {
    var matchFound = false;
    var isRow = false;

    _.each(columns, function (col) {
        if (option.value == col['ColumnCode']) {
            matchFound = true;
            isRow = col['IsRow']
            return false;
        }
    });

    if(matchFound && !isRow || !matchFound){
        $(this).attr('disabled', true); //jQuery pre 1.6
        //$(this).prop('disabled', true); // jQuery v1.6 or later
    }
});
如果这种情况是动态发生的,并且需要重置所有禁用的属性,只需在启动循环之前执行
model.Rows.find('option').removeAttr('disabled')
,或者如果使用jQuery 1.6或更高版本,则使用
model.Rows.find('option').prop('disabled',false)


-仅启用列表中且isRow设置为true的选项



仅限普通javascript?允许jQuery吗?允许jQuery,谢谢。您可能应该先使用
$(this).prop('disabled',true)
,然后使用
model.Rows.find('option')。prop('disabled',false)
@idbehold:虽然我只是专注于让解决方案发挥作用,但使用jQuery 1.6或更高版本时,您的建议绝对正确。正如jQuery中建议的那样,禁用的是DOM属性而不是属性。我编辑了答案以包含这些信息。