繁体   English   中英

禁用选项选择JavaScript

[英]Disable option select javascript

我有一个问题,我想启用/显示选项,如果该选项与“ 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元素:

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

有人可以指导吗?

您应该将循环从内到外翻转,然后首先遍历选项,然后遍历数组,否则您的选项将不断被重置,或者可能一直被禁用。

您可能还想添加类似于<option value="none">...please select</option>的默认选项, <option value="none">...please select</option>值以确保在禁用所有功能的情况下不会选择任何内容。

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)在开始循环之前model.Rows.find('option').prop('disabled', false)model.Rows.find('option').prop('disabled', false)


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


暂无
暂无

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

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