Disable all DropDownList Option's except whichever is selected

1

How to disable all options of a combo minus the value selected using JQuery.

As in the image below:

FollowtheHTMLintheimage:

HTML

<!DOCTYPEhtml><html><body><select><optiondisabledvalue="volvo">Volvo</option>
            <option disabled value="saab">Saab</option>
            <option selected value="opel">Opel</option>
            <option disabled value="audi">Audi</option>
        </select>
    </body>
</html>
    
asked by anonymous 27.02.2015 / 19:32

3 answers

3

You can also use the .not() function with the :selected and reduce the code to one line.

Example:

$('#opcoes option').not(':selected').prop('disabled', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="opcoes">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel" selected>Opel</option>
    <option value="audi">Audi</option>    
</select>
    
27.02.2015 / 19:53
4

Although the answer from @DiegoZanardo is correct, I would like to add a complete example.

In this case I used the :not(:selected) selector to filter the options.

var btTravar = $("#btTravar");
var slMarcas = $("#slMarcas");
btTravar.click(function () {
    var options = slMarcas.children("option:not(:selected)");
    options.prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="slMarcas">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
</select>
<input id="btTravar" type="button" value="Travar" >
    
27.02.2015 / 19:53
1

You need to go through all options and then add disabled to options that are not select :

    $(function() {
        $("#mySelect > option").each(function(i){
            if(!($(this).is(':selected'))){
                $(this).attr('disabled',true);
            }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><selectid="mySelect">
        <option  value="Volvo">Volvo</option>
        <option  value="Saab">Saab</option>
        <option  selected value="Opel">Opel</option>
        <option  value="Audi">Audi</option>
    </select>
    
27.02.2015 / 19:44