Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable option in dropdown list based on selection in other list

I have the following code

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

And then have 3 dropdown lists

<select name="vote1" id="vote1">
<option value="player1">Player1</option>
<option value="player2">Player2</option>
<option value="player3">Player3</option>
<option value="player4">Player3</option>
</select>
<select name="vote2" id="vote2">
<option value="player1">Player1</option>
<option value="player2">Player2</option>
<option value="player3">Player3</option>
<option value="player4">Player3</option>
</select>
<select name="vote3" id="vote3">
<option value="player1">Player1</option>
<option value="player2">Player2</option>
<option value="player3">Player3</option>
<option value="player4">Player3</option>
</select>

With my code when you select 1 item it disables it in the dropdown list of the other two iteams, however if I then click on another option in another list, it enables the options in the others.

I want to be able to select the option in one dropdown list and it stays disabled in all the other dropdown lists until it is deselected.

Is this possible?

JS fiddle

like image 686
Dannymh Avatar asked Feb 02 '15 16:02

Dannymh


1 Answers

This is pretty much the same as what you already had, except it loops over each select each time one changes, and disables the option selected in the other selects:

var $selects = $('select');

$selects.on('change', function() {

    // enable all options
    $selects.find('option').prop('disabled', false);

    // loop over each select, use its value to 
    // disable the options in the other selects
    $selects.each(function() {
       $selects.not(this)
               .find('option[value="' + this.value + '"]')
               .prop('disabled', true); 
    });

});

Here's a fiddle

like image 126
billyonecan Avatar answered Sep 19 '22 05:09

billyonecan