Disable option in dropdown list based on selection in other list

放肆的年华 提交于 2020-01-31 05:39:03

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/28281916/disable-option-in-dropdown-list-based-on-selection-in-other-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!