Search code examples
jquerydrop-down-menu

JQuery Remove Options Where id != Other Selected Option


I think this is a simple syntax problem. I have a list of states and a list of cities. Once the user selects a state, I want to use Jquery to remove all options but those in the selected state.

Script:

<script>
$(function(){
$('#state').change(function(){
    var selstate = $('#state:selected').text();
    $('.city:not(#'+selstate+')').remove();

});
});

</script>

HTML:

<select id="state" name='State'> 
    <option value="AL">Alabama</option> 
    <option value="AK">Alaska</option>
</select>

<select id="city" name='City'> 
    <option class="AL" value="City A">City A</option>
        <option class="AL" value="City B">City B</option>
    <option class="AK" value="City C">City C</option>
    <option class="AK" value="City D">City D</option>
</select>

Solution

  • Try this:-

    $(function () {
        $('#state').change(function () {
            var selstate = $(this).val();
            $('#city option').not('.' + selstate).remove();
        });
    });
    

    I am not sure you really want to remove the options, probably disable would be a better option.

    Demo

    $(function () {
        $('#state').change(function () {
            var selstate = $(this).val();
            $('#city option').prop('disabled', false).not('.' + selstate).prop('disabled',true);
            $('#city option').not('[disabled]').eq(0).prop('selected',true); 
            // Clear current selection to the first city for the new state
        });
    });
    

    Update Hide and show options (Doesnot work in all browsers):-

    Hide the unwanted dropdown instead of removing them:-

    Demo

    Script

    $(function () {
        $('#state').change(function () {
             var selstate = $(this).val();
             $('#city option').addClass('hidden');
             $('#city option.hidden').not('.' + selstate).removeClass('hidden');
             $('#city option').not('.hidden').eq(0).prop('selected',true);
         });
    });
    

    Css

    .hidden
    {
        display:none;
    }
    

    Update 2:- Store the options as data and reconstruct the select.

    Demo

    $(function(){
    
        $('#state').data('city', $('#city option'));//Store the options initially in data.
    
        $(function () {
            $('#state').change(function () {
                 var selstate = $(this).val();
                 var options = $(this).data('city');
                   $('#city').html(options.filter(function(){return this.className === selstate}));
             });
        });
    });