我有一个HTML表单,其中包含四个名称的下拉列表。
window.onload = function(){
document.getElementById("submit").onclick = showStudents;
}
function showStudents(){
if(document.getElementById("mary jones").value == "mary jones"){
document.getElementById("students").innerHTML = "Mary Jones";
}
else if(document.getElementById("jane doe").value == "jane doe"){
document.getElementById("students").innerHTML = "Jane Doe";
}
else if(document.getElementById("henry miller").value == "henry miller"){
document.getElementById("students").innerHTML = "Henry Miller";
}
else if(document.getElementById("john smith").value == "john smith"){
document.getElementById("students").innerHTML = "John Smith";
}
}
<div id="students">
<form id="getStudent" action="" method="GET">
<select name="students">
<option value="john smith" id="john smith">John Smith</option>
<option value="jane doe" id="jane doe">Jane Doe</option>
<option value="henry miller" id="henry miller">Henry Miller</option>
<option value="mary jones" id="mary jones">Mary Jones</option>
</select>
<br><br>
<input id="submit" type="submit">
</form>
当我单击提交时,将调用一个Javascript函数,并且我想显示我选择的学生的姓名,但是它仅显示第一个if语句的结果。我的想法是我需要将表单数据的值传递给函数,但不确定如何执行此操作。这是我提出的javascript代码。
最佳答案
您将需要使用选定的选项-当前,仅将其设置为“Mary Jones”,因为<option id="mary jones" value="mary jones">
的值始终为“Mary Jones”。使用.value
元素的<select>
属性获取所选选项的值:
function showStudents() {
var selected = document.getElementById("getStudent")["students"].value;
var output = document.getElementById("students");
if (selected == "mary jones") {
output.innerHTML = "Mary Jones";
} else if (selected == "jane doe") {
output.innerHTML = "Jane Doe";
} else if (selected == "henry miller") {
output.innerHTML = "Henry Miller";
} else {
output.innerHTML = "John Smith";
}
}
另外请记住,ID名称中不能有空格-因此
<option>
看起来应该像这样:<option value="mary jones" id="maryJones">Mary Jones</option>