Search code examples
jqueryhtmldrop-down-menuhtml-selectcascadingdropdown

Need to cacade options in dropdown


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.


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