Question

I have 3 dropdowns with same set of options as below

<select id="one">
<option value="1">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="two">
<option value="1">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="three">
 <option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

If user selects option "one" in third dropdown, "One" should not be displayed in 1nd and 2rd dropdown. At any point of time when user clicks on any dropdown, only the current value along with the values which are not selected in other dropdown should be displayed.

Is there any way to achieve this with jQuery

Please help.

Was it helpful?

Solution

Your HTML is invalid. You need to close <option> tag using </option>

You also need to give different value beside 1 such as -1 or leave it as blank for the first option inside each of your select

Then you can do like this to achieve your requirements:

$('select').change(function () {
    var selectedVal = $(this).val();
    $(this).siblings('select').find('option[value="' + selectedVal + '"]').hide();
    $(this).siblings('select').find(':not(option[value="' + selectedVal + '"])').show();
    $(this).siblings('select').find('option:eq(0)').prop('selected', true);
});

Fiddle Demo

OTHER TIPS

This can be handled using an event listener for your select dropdowns. In the event listener function get the selected value from the element that triggered the event.

Once you have the selected value, you can loop through other select dropdowns and remove the selected value.

Here is a short snippet of the code

    $('.dropdown').change(function (event) {
        $('.dropdown').each(function (index, element) {

            if (event.target.id == element.id) {
                return true;            
            }

            var selectedValue = event.target.value;
            $(element).children('[value=' + selectedValue + ']').remove();
        });
    });

Here is a complete working demo:

http://jsfiddle.net/399LF/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top