javascript 使用表单选择菜单在 HTML 中显示条件字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22441858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:09:55  来源:igfitidea点击:

Displaying conditional Fields in HTML Using A Form Select Menu

javascriptjqueryhtmlforms

提问by Derek O Brien

I am trying to get my page to display different form elements depending on which option is selected from the select menu but i can not get it to work for me

我试图让我的页面显示不同的表单元素,具体取决于从选择菜单中选择的选项,但我无法让它对我来说有效

my HTML is

我的 HTML 是

 <h3>Register For General Admission</h3>

<form action="GeneralRegister" method="POST" style="text-align:center">
Type Of Ticket: <select name="typeofticket" size="1" id="generalAdmissionList">
    <option value="1"></option>
    <option value="1">General Admission</option>
    <option value="1">General Admission School</option>
</select>
<br>
<div id="1">
    <!--for general admission-->
    First name:
    <input type="text" name="firstname">
    <br>Last name:
    <input type="text" name="lastname">
    <br>
</div>
<div id="2">
    <!--For Schools-->
    School name:
    <input type="text" name="school">
    <br>
</div>
Email:
<input type="text" name="email">
<br>
<input type="submit" value="Submit">
<br>
</form>

and my JavaScript is

我的 JavaScript 是

$("#generalAdmissionList").change(function () {
var selected = $("#generalAdmissionList option:selected").form();
$('div').hide();
$('#' + selected).show();
});

$(document).ready(function (e) {
$('div').hide();
});

any help would be great

任何帮助都会很棒

采纳答案by attila

Change your select options to this

将您的选择选项更改为此

<option value="1">General Admission</option>
<option value="2">General Admission School</option>

and the javascript line to get the selected value should be like this

并且获取选定值的 javascript 行应该是这样的

var selected = $("#generalAdmissionList option:selected").val();