JQuery Depending on the first dropdown / sorting of the second drop down list?

I have two dropdowns. The first lists the values, such as [--All--, Group1, Group2, Group3, etc.], and the second should include all values ​​by default. If we select β€œGroup 1” from the second, only those values ​​that are related should be listed. How do we achieve this in jQuery and html .. there is no database here.

+1
jquery html html-select
source share
1 answer

You can 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); }); 
+1
source share

All Articles