jquery / javascript隐藏和显示元素依赖下拉列表

时间:2013-03-16 12:42:19

标签: javascript jquery html

我需要在一个选择下拉列表中显示/隐藏选项,这取决于另一个下拉列表的选定选项。

我的意思是,当我选择“其他”时,会在花药下拉列表中显示(男性和女性)! 当我选择“先生工程师”时,那么只会显示“男性” 当我选择“miss。engineer”时,那将只显示“女性”。

<select>
<option value="">Choose</option>
<option value="Mr">Mr. Engineer</option>
<option value="Miss">Miss. Engineer</option>
<option value="other">Other</option>

</select>

<select>
<!--Below shows when 'Other' is selected , and show otherwise-->
<option value="0">choose</option>

<!--Below shows when 'Mr. engineer' is selected jsut , and hidden otherwise-->
<option value="male">Male</option>

<!--Below shows when 'Miss. engineer' is selected just, and hidden otherwise-->
<option value="female">Female</option>

</select>

2 个答案:

答案 0 :(得分:0)

您可以使用change并执行:

$("#dropdownlist").change(function() {
   var control = $(this);

   if (control.val() == "Engineer") {
      $("#dropdownlist2").show();
   }
});

这基于以下结构:

<select id="dropdown1">
   <option value="Mechanic">Mechanic </option>
   <option value="Engineer">Engineer</option>
 </select>

<select id="dropdown2" style="display:none">
   <option value="Item 1">Item 1 </option>
   <option value="Item 2">Item 2 </option>
 </select>

http://jsfiddle.net/zs3QG/

答案 1 :(得分:0)

在这种情况下,我通常会在HTML本身的选择之间映射值,并使用JS中的那些映射,而不是在JS中对它进行硬连接。

例如:appliesto属性映射select2中适用于select1中每个选项的选项。

<select id="one">
  <option>Choose</option>
  <option appliesto="male">Mr. Engineer</option>
  <option appliesto="female">Miss. Engineer</option>
  <option appliesto="other">Other</option>
</select>

<select id="two">
  <option type="other">choose</option>
  <option type="male">Male</option>
  <option type="female">Female</option>
</select>

并使用这些映射根据需要通过JS显示/隐藏。

$('select#one').change(function() {
    var selType = $(this).find('option:selected').attr('appliesto');
    $('select#two option[type="'+selType+'"]').prop('selected', true);
});

查看此演示:http://jsfiddle.net/xGJRP/1/

当然你可能需要进一步微调这一点,但我相信你明白了。