display dropdown values based on previous dropdown

2019-01-15 11:27发布

问题:

I have the following form fields:

        <label for="carrier_sold">Carrier Sold: </label>
        <select name="carrier_sold" id='carrier_sold'>
        <option id='carrier_sold' value="" selected="selected"></option>
        <option value="MetLife">Metlife</option>
        <option value="Travelers">Travelers</option>

        </select>

If I select the value Metlife I need to get Bill,Full as my dropdown value below.

If I select the value Travelers I need to get EFT,RCC as my drop down value below.

        <label for="payment_plan">Payment Plan: </label>
        <select name="payment_plan" id='payment_plan'>
        <option id='payment_plan' value="" selected="selected"></option>

Finally,if I select Metlife and Bill from the above 2 dropdowns, I need to display a radio button below.

        <label for="min_dp">Is minimum DP required? </label>
        <input type="radio" name="yes" value="Yes" />Yes
        <input type="radio" name="no" value="No" />No

else dont display the radio button.It's kinda overwhelming to do in jquery. Can someone point me to the correct direction

回答1:

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().



回答2:

Check Creating Cascading Dropdown List Using JQuery