Jam Dev Jam Dev - 1 month ago 8
jQuery Question

How to make the dropdown option disable in HTML web page

I have web page with three dropdown. It is working fine, except for one problem.

When we select any item from one dropdown then it is disabled in the other two dropdowns, but if we again select another item from first dropdown then it disables this item but it also disables the previously selected item.

The previously selected should be enabled when new option is disabled.

Here is the code:

<select id="select1" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>

<select id="select2" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>

<select id="select3" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>


Here is the JavaScript code:

$(document).ready(function(){
$("select").change(function() {
$("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true);
});
});


Demo Link: http://jsfiddle.net/x4E5Q/137/

Answer

Combine the focus event with the change event to achieve what you want:

DEMO: http://jsfiddle.net/abc123/x4E5Q/143/

$(document).ready(function () {
    var previous;

    $("select").focus(function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function () {
        // Do something with the previous value after the change

        $("select").not(this).find("option[value=" + previous + "]").prop('disabled', false);
        $("select").not(this).find("option[value=" + $(this).val() + "]").prop('disabled', true);
        // Make sure the previous value is updated
        previous = this.value;
    });
});