根据选择列表显示/隐藏某些字段

时间:2014-09-10 17:14:02

标签: javascript html

我正在尝试使用JavaScript和/或jQuery根据下拉菜单中选择的项目隐藏某些html元素。该页面如下所示:

[Drop down menu]

[text field 1]
[text field 2]
[text field 3]
[text field 4]
[text field 5]

下拉菜单有3个选项。对于第一个选项,应显示字段1-4。对于第二个,2-4,以及第三个字段2-5应该可用。

我有一个JSFiddle demo here。具体来说,我不明白为什么

<option value="option3.com" onselect="$('#five').hide()">option3.com</option>

不会隐藏'#five'

3 个答案:

答案 0 :(得分:1)

首先,没有onselect,你可能想要onchange 其次,你正在使用jQuery,所以使用它。
第三,更改标记以某种方式包含您想要的内容,数据属性非常好。

<select style="width: 120px;" name="farm_in" id="farm_in">
    <option></option>
    <option value="option1.com" data-show="[1,2,3,4]">option1.com</option>
    <option value="option2.com" data-show="[2,3,4]">option2.com</option>
    <option value="option3.com" data-show="[2,3,4,5]">option3.com</option>
</select>
<br>
<input style="width: 120px;" type="text" name="one" id="el1" value="one">
<br>
<input style="width: 120px;" type="text" name="two" id="el2" value="two">
<br>
<input style="width: 120px;" type="text" name="three" id="el3" value="three">
<br>
<input style="width: 120px;" type="text" name="four" id="el4" value="four">
<br>
<input style="width: 120px;" type="text" name="five" id="el5" value="five">

然后你所要做的就是

$('#farm_in').change(function() {
    $('input').hide();
    $('#el' + $('option:selected', this).data('show').join(', #el')).show();
});

FIDDLE

答案 1 :(得分:1)

首先,这不会识别DOM中的元素:

$('#five')

您没有id "five"的元素。相反,你正在寻找这个:

$('input[name="five"]')

(或者,相反,您可以为元素提供id属性。)

除此之外,我不知道onselect元素的任何option事件。为什么不回复change的{​​{1}}事件(并且当你在它时稍微脱离标记)?:

select

答案 2 :(得分:0)

看着你的小提琴你缺少文本字段的ID属性。

<input style="width: 120px;" type="text" name="five" value="five">

应该是:     

另外,我建议您从HTML中拆分JS。

相关问题