1

I have Two Dropdowns, The First one lists values like [--All--, Group1, Group2, Group3, etc] and the second one initially should list all values by default. If we select Group 1 from the second should list only those values related. How do we achive that in Jquery & html.. no database here.

adgfx
  • 13
  • 1
  • 7

1 Answers1

1

You may try something like this (using data-)

HTML:

<select id="groups">
    <option value='--All--'>--All--</option>
    <option value='Group1'>Group1</option>
    <option value='Group2'>Group2</option>
    <option value='Group3'>Group3</option>
</select>

<select id="sub_groups">
    <option data-group='all' value='0'>--Select--</option>
    <option data-group='Group1' value='one'>one</option>
    <option data-group='Group1' value='two'>two</option>
    <option data-group='Group2' value='three'>three</option>
    <option data-group='Group2' value='four'>four</option>
    <option data-group='Group3' value='five'>five</option>
    <option data-group='Group3' value='Six'>six</option>
<select>

JS:

$('#groups').on('change', function(){
    var val = $(this).val();
    var sub = $('#sub_groups');
    if(val == '--All--') {
        $('#sub_groups').find('option').show();
    }
    else {
        sub.find('option').not(':first').hide();
        $('option', sub).filter(function(){
            if($(this).attr('data-group') == val){
                $(this).show();
            }
        });
    }
    sub.val(0);
});
The Alpha
  • 143,660
  • 29
  • 287
  • 307