jQuery - 禁用所选选项

Jef*_*rey 56 jquery html-select

需要使用jQuery在选择框中禁用已选择的选项.我希望它像asmselect一样变灰.

在这里测试我的例子.

//JS
$("#theSelect").change(function(){          
  var value = $("#theSelect option:selected").val();
  var theDiv = $(".is" + value);

  theDiv.slideDown().removeClass("hidden");
});


$("div a.remove").click(function () {     
  $(this).parent().slideUp(function() { $(this).addClass("hidden"); }); 
});

//HTML
<body>
<div class="selectContainer">
    <select id="theSelect">
        <option value="">- Select -</option>
        <option value="Patient">Patient</option>
        <option value="Physician">Physician</option>
        <option value="Nurse">Nurse</option>
    </select>
</div>
<div class="hidden isPatient">Patient <a href="#" class="remove" rel="Patient">remove</a></div>
<div class="hidden isPhysician">Physician <a href="#" class="remove" rel="Patient">remove</a></div>
<div class="hidden isNurse">Nurse <a href="#" class="remove" rel="Patient">remove</a></div>
</body>?
Run Code Online (Sandbox Code Playgroud)

更新:这是完成的解决方案.感谢Patrick和Simen.

use*_*716 113

将此行添加到change事件处理程序中

    $("#theSelect option:selected").attr('disabled','disabled')
        .siblings().removeAttr('disabled');
Run Code Online (Sandbox Code Playgroud)

这将禁用所选选项,并启用任何先前禁用的选项.

编辑:

如果您不想重新启用之前的那些,只需删除该行的这一部分:

        .siblings().removeAttr('disabled');
Run Code Online (Sandbox Code Playgroud)

编辑:

http://jsfiddle.net/pd5Nk/1/

要在单击"删除"时重新启用,请将其添加到单击处理程序中.

$("#theSelect option[value=" + value + "]").removeAttr('disabled');
Run Code Online (Sandbox Code Playgroud)

  • @ user113716请使用`.prop('disabled',true);`因为在这种情况下更推荐使用. (3认同)

Sim*_*olt 6

这将分别在您选择/删除选项时禁用/启用选项.

$("#theSelect").change(function(){          
    var value = $(this).val();
    if (value === '') return;
    var theDiv = $(".is" + value);

    var option = $("option[value='" + value + "']", this);
    option.attr("disabled","disabled");

    theDiv.slideDown().removeClass("hidden");
    theDiv.find('a').data("option",option);
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    $(this).data("option").removeAttr('disabled');
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/AaXkd/


Siv*_*and 6

请尝试一下

$('#select_id option[value="'+value+'"]').attr("disabled", true);
Run Code Online (Sandbox Code Playgroud)


jea*_*eis 5

这似乎有效:

$("#theSelect").change(function(){          
    var value = $("#theSelect option:selected").val();
    var theDiv = $(".is" + value);

    theDiv.slideDown().removeClass("hidden");
    //Add this...
    $("#theSelect option:selected").attr('disabled', 'disabled');
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    //...and this.
    $("#theSelect option:disabled").removeAttr('disabled');
});
Run Code Online (Sandbox Code Playgroud)