1

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 Answer 1

7

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 :)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! It works but it causes another problem... After adding the code, the selected options values can't be posted to the form when I can't the submit button.. I don't know why it is happening..
i dont really follow what you meant, can you set up a jsfiddle for your issue
On your jsfiddle, if you have selected '2' on the first dropdown, and when you inspect element using Chrome, you can see that the selected option becomes <option value="2" disabled="disabled">2</option>, that means the option of the selected dropbox is also disabled. HTML don't post the disabled values to forms, so it's the problem. Thanks!
fixed the above mentioned issue, check now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.