How to prevent duplicate values in multiple dropdo

2019-06-14 04:23发布

问题:

I have 5 dropdowns menu for users to select their preferences. All the dropdowns have the same choices. If the user has chosen a value for dropdown 1, that option should not be available for the other dropdowns. And it goes on so, for the last dropdown, there should be 4 unselectable options.

It's similar to what is done on this link. But now we have more than 2 dropdowns.

(For illustration, I show three dropdowns only)    

<select id="_go">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="_gogo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="_gogogo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

The below codes works fine for two dropdowns, but not for more than 2.

var $select = $("select[id$='go']");
$select.change(function() {
    $select
      .not(this)
      .find('option')
      .prop('disabled', '')
      .filter('[value='+this.value+']')
      .prop('disabled','disabled');
});
$select.eq(0).trigger('change');

I thing to notice is that a user may accidentally clicked for a wrong option for one of the dropdowns, so if the user select again, the original value should be enabled again.

Please suggest a way. Thanks in advance.

回答1:

Instead of changing the status of the option right away, first you need to get current values in the select fields, so that you can disable them in other select fields

demo

 $(".go").change(function(){
    var selVal=[];
    $(".go").each(function(){
        selVal.push(this.value);
    });

    $(this).siblings(".go").find("option").removeAttr("disabled").filter(function(){
       var a=$(this).parent("select").val();
       return (($.inArray(this.value, selVal) > -1) && (this.value!=a))
    }).attr("disabled","disabled");
});

$(".go").eq(0).trigger('change');


the above code can be used with any number of select boxes :)