Home > Enterprise >  hiding second select option based on first select option
hiding second select option based on first select option

Time:05-20

I have 2 selects. Both have the same options (taken from db). Let's say the options are:

Inventory 1
Inventory 2
Inventory 3

If I choose Inventory 1 in the first select, then in the second select it should disappear. If I choose Inventory 2 in the first select, then Inventory 1 should appear back in the second select and Inventory 2 should disappear.

This is my code so far:

$('#from-location').on('change', function() {
        from_location_value = $('#from-location option:selected').val();
        to_location_value = $('#to-location option:selected').val();

        $("#to-location option[value="   from_location_value   "]").hide();
        
    });

CodePudding user response:

Try this

$('#from-location').on('change', function() {
    let fromValue = $('#from-location').val();
    let options = $('#to-location option').show();
    if( $(this).val() !== '' ){
        options.siblings('option[value="'   fromValue   '"]').hide()
    }
});
$('#to-location').on('change', function() {
    let toValue = $('#to-location').val();
    let options = $('#from-location option').show();
    if( $(this).val() !== '' ){
        options.siblings('option[value="'   toValue   '"]').hide()
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="from-location">
    <option value=""></option>
    <option value="Inventory 1">Inventory 1</option>
    <option value="Inventory 2">Inventory 2</option>
    <option value="Inventory 3">Inventory 3</option>
</select>
<select id="to-location">
    <option value=""></option>
    <option value="Inventory 1">Inventory 1</option>
    <option value="Inventory 2">Inventory 2</option>
    <option value="Inventory 3">Inventory 3</option>
</select>

  • Related