I have the following form fields:
You need to reference the parent in each child. Carrier:
<label for="carrier_sold">Carrier Sold: </label>
<select name="carrier_sold" id="carrier_sold">
<option value="" selected="selected">Select...</option>
<option value="MetLife">Metlife</option>
<option value="Travelers">Travelers</option>
</select>
Travelers: store the parent for each option, for example in a data-xyz
attribute.
<label for="payment_plan">Payment Plan: </label>
<select name="payment_plan" id="payment_plan">
<option value="" selected="selected">Select...</option>
<option data-parent="MetLife" value="bill">Bill</option>
<option data-parent="MetLife" value="full">Full</option>
<option data-parent="Travelers" value="eft">EFT</option>
<option data-parent="Travelers" value="rcc">RCC</option>
</select>
The jQuery:
$('#carrier_sold').change(function() {
var parent = $(this).val();
$('#payment_plan').children().each(function() {
if($(this).data('parent') != parent) {
$(this).hide();
} else $(this).show();
});
});
Repeat for the next instance. Ideally, I'd make a class-based jQuery function that works off of classes instead of IDs, and pulls the respective children from each parent via a data-child
attribute or similar.
And to jazz it up even more, you could hide the child unless the parent has a value. You can also experiment with change()
vs. blur()
.
Check Creating Cascading Dropdown List Using JQuery