问题描述
我试图使用JavaScript和/或jQuery来隐藏某些html元素,这些元素是基于在下拉菜单中选择哪个项目。该页面如下所示:
[下拉菜单]
[文本字段1]
[文本字段2]
[文本字段3]
[文本字段4]
[文本字段5]
下拉菜单有3个选项。对于第一个选项,字段1-4应显示。对于第二个,2-4和第三个字段2-5应该是可用的。
我有一个。具体来说,我不明白为什么
< option value =option3.comonselect =$('#five ).hide()> option3.com< /选项>
不隐藏'#five'
onchange
。 其次,您使用的是jQuery,因此使用它。
第三,将标记更改为包含所需内容,数据属性非常好。
< select style =width:120px; name =farm_inid =farm_in>
< option>< / option>
< option value =option1.comdata-show =[1,2,3,4]> option1.com< / option>
< option value =option2.comdata-show =[2,3,4]> option2.com< / option>
< option value =option3.comdata-show =[2,3,4,5]> option3.com< / option>
< / select>
< br>
< input style =width:120px; type =textname =oneid =el1value =one>
< br>
< input style =width:120px; type =textname =twoid =el2value =two>
< br>
< input style =width:120px; type =textname =threeid =el3value =three>
< br>
< input style =width:120px; type =textname =fourid =el4value =four>
< br>
< input style =width:120px; type =textname =fiveid =el5value =five>
然后你所要做的就是
<$ ($'code> $('#farm_in')。change(function(){
$('input')。hide();
$('#el'+ $('option:selected',this).data('show')。join(',#el'))。show();
});
I am attempting to use JavaScript and/or jQuery to hide certain html elements based on which item is selected in a drop down menu. The page looks like this:
[Drop down menu]
[text field 1]
[text field 2]
[text field 3]
[text field 4]
[text field 5]
The drop down menu has 3 options. For the first option, fields 1-4 should show. For the second, 2-4, and for the third fields 2-5 should be available.
I've got a JSFiddle demo here. Specifically, I don't get why
<option value="option3.com" onselect="$('#five').hide()">option3.com</option>
doesn't hide '#five'
Firstly, there is no onselect
, you probably wanted onchange
.
Secondly, you're using jQuery, so use it.
Thirdly, change the markup to somehow include what you want, data attributes are great.
<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">
Then all you have to do is
$('#farm_in').change(function() {
$('input').hide();
$('#el' + $('option:selected', this).data('show').join(', #el')).show();
});
这篇关于根据选择列表显示/隐藏某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!