2010-03-09 36 views
0

如何在選擇表單中選擇一個選項的值並將其用於if else語句?使用javascript時你如何使用select form來做else if語句?

例如,如果選擇apple作爲選項,然後寫入文檔如何製作蘋果醬,但選擇橙色,然後寫入如何製作橙色?

到目前爲止,我有一個基本形式和選擇選項,我知道怎麼做的文件撰寫,但我不知道如何使用一個選擇形式的if else

感謝您的幫助

回答

1

首先,確保你有你的<select>id讓你從JavaScript引用它:

<select id="fruits">...</select> 

現在,您可以使用您<select>的JavaScript的代表性optionsselectedIndex字段訪問當前選定值:

var fruits = document.getElementById("fruits"); 
var selection = fruits.options[fruits.selectedIndex].value; 

if (selection == "apple") { 
    alert("APPLE!!!"); 
} 
0

你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 
} 
+0

我認爲你是混合的東西。看起來你正在使用jQuery-ish選擇器函數,但你只寫了「if('#Dropdown')」。 另外,儘可能使用===。 – janmoesen 2010-03-09 07:34:58

+0

對不起,修正了。當我認爲JavaScript我認爲jQuery。 – 2010-03-09 07:36:45

0
var select = document.getElementById('myList'); 
if (select.value === 'apple') { 
    /* Applesauce */ 
} else if (select.value === 'orange') { 
    /* Orange */ 
}
0

或者您可以這樣做。

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>