2013-03-16 53 views
1

我需要显示在一个选择删除/隐藏选项下依赖于另一个下拉列表的选择的选项。的jQuery/JavaScript的隐藏和显示元件依赖下拉列表

我的意思是,当我选择“其他”,然后会显示在花药下拉名单(男&女)!然后 当我选择“MR。工程师”将只显示“男” ,当我选择“小姐。工程师”,那么将只显示“女性”。

<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> 

回答

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/

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/

当然,你可能需要微调这进一步,但我相信你的想法。

+0

**我的意思是,当我选择“其他”,然后会显示在花药下拉 完整列表(女性及男性)! 当我选择“MR。工程师”,那么将显示一个男只是 等。 。 。 ** – 2013-03-16 13:07:04

+0

相应地编辑了答案,也检查了更新后的演示。 – techfoobar 2013-03-16 13:49:00