Disable select options based on value *through the HTML only!*

前端 未结 4 669
囚心锁ツ
囚心锁ツ 2020-12-09 16:41

I need to disable a select option based on the value of a variable. The value is similar to one of the select option value and it needs to be disabled.

For ex,

相关标签:
4条回答
  • 2020-12-09 17:17
    $("select option[value='"+ $variable + "']").attr('disabled', true); 
    
    0 讨论(0)
  • 2020-12-09 17:19

    Let's say you had the following markup

    <select>
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
    

    Using this jQuery, the saab option would be disabled.

    $("select option").each(function() {
        var $thisOption = $(this);
        var valueToCompare = "saab";
    
        if($thisOption.val() == valueToCompare) {
            $thisOption.attr("disabled", "disabled");
        }
    });
    

    Try it out here

    0 讨论(0)
  • 2020-12-09 17:25

    This should be a faster solution

    $('select').children('option[value="' + $variable + '"]').attr('disabled', true)
    
    0 讨论(0)
  • 2020-12-09 17:27

    With your current markup this will work:

    $("select option:contains('Value b')").attr("disabled","disabled");
    

    http://jsfiddle.net/CtqC6/

    EDIT

    http://jsfiddle.net/CtqC6/1/

    var variable = "b"
    $("select option:contains('Value " + variable + "')").attr("disabled","disabled");
    $("select").prop("selectedIndex",-1)
    
    0 讨论(0)
提交回复
热议问题