动态填充下拉菜单

时间:2016-08-22 17:47:57

标签: jquery css forms menu dropdown

当您在第一个菜单上进行选择时,填充下拉菜单的最佳方法是填充第二个菜单以仅显示某些项目?这是我的代码。

<span class="title"><strong>Bag Model*</strong></span>
<label for="dwfrm_emailsignup_customer_fname"></label>
<select name="c_Consumers[address_state]" class="required errorclient" style="width:160px;" id="c_Consumers[address_state]">
<option selected="selected" value="">Select...</option>
<option value="FlexTech">FlexTech</option>
<option value="FlexTech-Lite">FlexTech Lite</option>
<option value="FlexTech-Crossover">FlexTech Crossover</option>
<option value="FlexTech-Single">FlexTech Single Strap</option>
<option value="Supreme-Cart">Supreme Cart Bag</option>
<option value="TM-Cart">TM Cart Lite</option>
<option value="Custom">Custom Bag</option>

</select>

<span class="title2"><strong>Bag Color</strong></span>
<label for="dwfrm_emailsignup_customer_fname"></label>
<select name="c_Consumers[address_state]" class="required errorclient" style="width:160px;" id="c_Consumers[address_state]">
<option selected="selected" value="">Select...</option>
<option value="Black">Black</option>
<option value="Camo">Camo</option>
<option value="Dark-Gray-Green">Dark Gray/Green</option>
<option value="Lite-Gray-Black">Lite Gray/Black</option>
<option value="Lite-Gray-Red">Lite Gray/Red</option>
<option value="Lite-Gray-Yellow">Lite Gray/Yellow</option>
<option value="Green-White">Green/White</option>
<option value="Navy">Navy</option>
<option value="Red">Red</option>
<option value="Royal">Royal</option>
<option value="White-Red">White/Red</option>
<option value="White-Royal">White/Royal</option>

</select>

1 个答案:

答案 0 :(得分:0)

在第二个下拉列表中更改所选值的简单jQuery代码段如下所示:

$('#firstDropdown').change(function(){
  if(this.value === 'FlexTech'){
    $('#secondDropdown').html('<option selected="selected" value="">Select...</option>'+'<option value="Green-White">Green/White</option>'+
        '<option value="Navy">Navy</option><option value="Red">Red</option>'+
        '<option value="Royal">Royal</option><option value="White-Red">White/Red</option>'+
         '<option value="White-Royal">White/Royal</option>');
  } else {
    $('#secondDropdown').html('');
  }
});

相应地替换ID,方括号不起作用。 可以在这里找到工作示例: http://codepen.io/westefan/pen/BzZROj