如何根据</option> <option selected =“”>禁用<option>?

时间:2016-11-23 11:48:09

标签: javascript jquery html html-select

我有一个用户列表,每个用户都有一个角色。

被选为“Líder”的用户不能有多个角色,只能“Líder”。

如果用户选择其他选项(女儿),则应禁用“Líder”选项。不是“Líder”的用户可以有多个角色。

以下是问题的模拟:jsfiddle

HTML:

<select class="selectpicker" id="funcao" multiple data-max-options="1">
  <option value="lider">Líder</option>
  <option value="conhecimento">Para Conhecimentor</option>
  <option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
  <option value="lider">Líder</option>
  <option value="conhecimento">Para Conhecimentor</option>
  <option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
  <option value="lider">Líder</option>
  <option value="conhecimento">Para Conhecimentor</option>
  <option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
  <option value="lider">Líder</option>
  <option value="conhecimento">Para Conhecimentor</option>
  <option value="participante">Participante</option>
</select>

JS:

$('select').change(function(){
    var sel = $(this); 
    var data = sel.data('prev'); 
    var val = sel.val();
    var prev; 
    if(data){ prev = data.val; }
    sel.data('prev', {val: val}); 
    sel.nextAll().each(function(){
        if(prev){
            $(this).find("[value='" + prev+ "']").prop("disabled",false);
            $('.selectpicker').selectpicker('refresh');
        }
        $(this).find("[value='" + val + "']").prop("disabled",true);
        $('.selectpicker').selectpicker('refresh');
    });
    $('.selectpicker').selectpicker('refresh');
});

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码检查效果 - jsfiddle

$('select').change(function() {
    var sel = $(this);
    disableThis(sel);
    $('.selectpicker').selectpicker('refresh');
});

function disableThis(sel) {
    var temSelecionado = false;

    $("option[value='1']").each(function() {
        if (this.selected) {
            temSelecionado = true;

            $(this).parent().each(function() {
                $(this.options).each(function() {
                    if ($(this).val() != "1") {
                        $(this).prop("disabled", true);
                    }
                })
            });
        }
        else {
                $(this).parent().each(function() {
                $(this.options).each(function() {
                    if ($(this).val() != "1") {
                        $(this).prop("disabled", false);
                    }
                })
            });
        }
    }); 
}