Disable all Dropdownlist Options s less what is selected

Asked

Viewed 995 times

1

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

As in the image below:

inserir a descrição da imagem aqui

Follow the HTML in the image:

HTML

<!DOCTYPE html>
<html>
    <body>
        <select>
            <option disabled value="volvo">Volvo</option>
            <option disabled value="saab">Saab</option>
            <option selected value="opel">Opel</option>
            <option disabled value="audi">Audi</option>
        </select>
    </body>
</html>

3 answers

4

Although @Diegozanardo’s reply is correct, I’d like to add a full example.

In this case I used the selector :not(:selected) 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>
<select id="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" >

  • Very good... :) +1

  • Much simpler than my +1 answer.

  • Very interesting, worth the tip!

3


You can also use the function .not() with the selector :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>
<select id="opcoes">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel" selected>Opel</option>
    <option value="audi">Audi</option>    
</select>

  • while I was writing my answer, you had the same idea.

  • I didn’t know . not yet... I liked the simplicity too +1;

  • @Tobymosque At the exact moment I clicked to send your answer appeared :). It must have been a difference of about 3 seconds.

1

You need to go through all the options and then add the disabled us options who are not with 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>
<select id="mySelect">
        <option  value="Volvo">Volvo</option>
        <option  value="Saab">Saab</option>
        <option  selected value="Opel">Opel</option>
        <option  value="Audi">Audi</option>
    </select>

  • It’s always good to have varied views to solve a problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.