I am trying to get a second dropdown based on first dropdown selection.
I found a great script here:
http://jsfiddle.net/heera/Gyaue/
enter code here
From this post: Jquery Depending on the first Dropdown display/sort a second dropdown?
However this example shows a "-- All --" option showing all the groups together and I need to do something just like
Dropdown A
America
Europe
Asia
Dropdown B
(if America is selected)
Argentina
Brazil
Chile
(if Europe is selected)
Italy
France
Spain
(if Asia is selected)
China
Japan
What I'm trying to get is the same shown on that jsfiddle but I don't want to have a "Show all (groups)" together option.
Update: After many tries I ended up using the solution posted by Catalin Berta on his website at: http://devingredients.com/2011/05/populate-a-select-dropdown-list-with-jquery/
The final result from that URL is something like this: http://jsfiddle.net/c510xdrj/
This solution works on all major browsers.
Thanks to Shlomi Hassid for your help.
I don't see where the problem is just drop the part that correspond to the all stuff and you are done.
Take a look: JSnippet Demo
jQuery:
$(function(){
$('#groups').on('change', function(){
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function(){
if (
$(this).attr('data-group') === val
|| $(this).attr('data-group') === 'SHOW'
) {
$(this).show();
} else {
$(this).hide();
}
});
});
$('#groups').trigger('change');
});
HTML:
<select id="groups">
<option value='America'>America</option>
<option value='Europe'>Europe</option>
<option value='Asia'>Asia</option>
<select>
<select id="sub_groups">
<option data-group='SHOW' value='0'>-- Select --</option>
<option data-group='America' value='Argentina'>Argentina</option>
<option data-group='America' value='Brazil'>Brazil</option>
<option data-group='America' value='Chile'>Chile</option>
<option data-group='Europe' value='Italy'>Italy</option>
<option data-group='Europe' value='France'>France</option>
<option data-group='Europe' value='Spain'>Spain</option>
<option data-group='Asia' value='China'>China</option>
<option data-group='Asia' value='Japan'>Japan</option>
<select>
EDIT As mentioned in the comments this method is not supported by safari. here is a second solution that should work on any modern browser:
JSnippet DEMO
jQuery:
$(function(){
$('#groups').on('change', function(){
var val = $(this).val();
var sub = $('#sub_groups');
$('option', sub).filter(function(){
if (
$(this).attr('data-group') === val
|| $(this).attr('data-group') === 'SHOW'
) {
if ($(this).parent('span').length) {
$(this).unwrap();
}
} else {
if (!$(this).parent('span').length) {
$(this).wrap( "<span>" ).parent().hide();
}
}
});
});
$('#groups').trigger('change');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With