我本质上是想有一个表格。然后,当您提交时,它只会打印出您从下拉列表中选择的值。然而我得到的只是 undefined undefined
<form action="items" method="get">
Fruits
<select name="fruits">
<option value="apple">Apple</option>
<option value="mango">Mango</option>
<option value="all-fruits">All Fruits</option>
</select>
<br/>
Vegs:
<select name="vegs">
<option value="carrots">Carrots</option>
<option value="peas">Peas</option>
<option value="Lettuce">Lettuce</option>
</select>
<br>
<input type="button" value="Submit" onClick="show_selection()"><br>
Your Selection: <span id="result"></span>
<script>
function show_selection() {
document.getElementById("result").innerHTML = document.getElementsByName('fruits').value + " " +
document.getElementsByName('vegs').value;
}
</script>
如果您在 fruits
部分中选择 All Fruits
并在 vegs
部分中选择 Peas
,则应打印全果豌 bean
最佳答案
您的问题是 document.getElementsByName
返回 node-list收藏。这意味着此集合中可能有多个从 HTML 中检索的元素,因为它们都具有相同的名称
。因此,如果您只想从此集合中获取一个元素,则需要使用索引 0
来定位该元素。
请参阅下面的工作示例:
<form action="items" method="get">
Fruits
<select name="fruits">
<option value="apple">Apple</option>
<option value="mango">Mango</option>
<option value="all-fruits">All Fruits</option>
</select>
<br/>
Vegs:
<select name="vegs">
<option value="carrots">Carrots</option>
<option value="peas">Peas</option>
<option value="Lettuce">Lettuce</option>
</select>
<br>
<input type="button" value="Submit" onClick="show_selection()"><br>
Your Selection: <span id="result"></span>
<script>
function show_selection() {
let selectedFruit = document.getElementsByName('fruits')[0].value;
let selectedVeg = document.getElementsByName('vegs')[0].value;
if(selectedVeg == "peas") {
selectedVeg = "Peas!!!";
}
document.getElementById("result").innerHTML = selectedFruit + " " +selectedVeg;
}
</script>
编辑:如果您查看上面的代码片段,您会发现我已将两个选定的选项存储在它们自己的变量中。然后,您可以使用 if
语句检查变量是否等于特定字符串(例如:peas
),然后相应地更改变量,以便更新输出的文本.
另一个解决方案是为您的 select
元素提供一个 id
。由于每个元素的 id 必须是唯一的,因此您可以使用 document.getElementById 来获取单个元素而不是一组元素:
<form action="items" method="get">
Fruits
<select id="fruits">
<option value="apple">Apple</option>
<option value="mango">Mango</option>
<option value="all-fruits">All Fruits</option>
</select>
<br/>
Vegs:
<select id="vegs">
<option value="carrots">Carrots</option>
<option value="peas">Peas</option>
<option value="Lettuce">Lettuce</option>
</select>
<br>
<input type="button" value="Submit" onClick="show_selection()"><br>
Your Selection: <span id="result"></span>
<script>
function show_selection() {
document.getElementById("result").innerHTML = document.getElementById('fruits').value + " " +
document.getElementById('vegs').value;
}
</script>
关于javascript - 提交表单时出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894257/