【发布时间】:2010-03-09 07:30:40
【问题描述】:
如何在选择表单中获取选项的值并将其用于 if else 语句?
例如,如果选择了苹果作为选项,则在文档中写入如何制作苹果酱但选择了橙子,然后写入如何制作橙子?
到目前为止,我有一个基本的表单和选择选项,并且我知道如何执行 document.write,但我不知道如何将选择表单与 if else 一起使用
感谢您的帮助
【问题讨论】:
标签: javascript select if-statement
如何在选择表单中获取选项的值并将其用于 if else 语句?
例如,如果选择了苹果作为选项,则在文档中写入如何制作苹果酱但选择了橙子,然后写入如何制作橙子?
到目前为止,我有一个基本的表单和选择选项,并且我知道如何执行 document.write,但我不知道如何将选择表单与 if else 一起使用
感谢您的帮助
【问题讨论】:
标签: javascript select if-statement
首先,确保您的<select> 上有一个id,允许您从Javascript 中引用它:
<select id="fruits">...</select>
现在,您可以在 <select> 的 Javascript 表示中使用 options 和 selectedIndex 字段来访问当前选定的值:
var fruits = document.getElementById("fruits");
var selection = fruits.options[fruits.selectedIndex].value;
if (selection == "apple") {
alert("APPLE!!!");
}
【讨论】:
var select = document.getElementById('myList');
if (select.value === 'apple') {
/* Applesauce */
} else if (select.value === 'orange') {
/* Orange */
}
【讨论】:
您的 HTML 标记
<select id="Dropdown" >
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select>
你的 JavaScript 逻辑
if(document.getElementById('Dropdown').options[document.getElementById('Dropdown').selectedIndex].value == "Apple") {
//write applesauce
}
else {
//everything else
}
【讨论】:
===。
您也可以这样做。
var fruitSelection = document.formName.optionName; /* if select has been given an name AND a form have been given a name */
/* or */
var fruitSelection = document.getElementById("fruitOption"); /* If <select> has been given an id */
var selectedFruit = fruitSelection.options[fruitSelection.selectedIndex].value;
if (selectedFruit == "Apple") {
document.write("This is how to make apple sauce....<br />...");
} else {
}
//HTML
<!-- For the 1st option mentioned above -->
<form name="formName">
<select name="optionName> <!-- OR -->
<select id="optionName">
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
<option value="Peach">Peach</option>
</select>
</form>
【讨论】: