lewis4u lewis4u -4 years ago 91
HTML Question

How to disable non selected options in select boxes using jQuery?

I have a model in Laravel that can be edited with dynamic form but i want to prevent changing the selected option in select box so when i open the edit page i should be able to see the select boxes with selected items but all other options should be disabled.

Maybe i could just select all

select
with jQuery and disable all non selected values?? How to do that?

I have tried this:

// disable non selected items
$('select').each(function(){
$('option').each(function() {
if(this.selected) {
this.attr('disabled', true);
}
});
});


But it doesn't work, i just need a little help

this is the select box and all others are the same:

<select name="car">
<option selected="selected" value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>


just other values selected

Answer Source

Your code has two problem. First: you should check if option isn't selected (!this.selected) then disable it. Second: this.attr('disabled', true) doesn't work in jquey. You should use $(this) instead.

$('select').each(function(){
    $('option').each(function() {
        if(!this.selected) {
            $(this).attr('disabled', true);
        }
    });
});

$('select').each(function(){
    $('option').each(function() {
        if(!this.selected) {
            $(this).attr('disabled', true);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="car">
  <option selected="selected" value="1">Volvo</option>
  <option value="2">Saab</option>
  <option value="3">Mercedes</option>
  <option value="4">Audi</option>
</select>

Note that first .each() loop in you code is additional. The bottom code is enough.

$('option').each(function() {
  !this.selected ? $(this).attr('disabled', true) : "";
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download