views:

127

answers:

4

How do you take a value of an option in a select form and use it for a if else statement?

for example if apple is selected as an option then write to the document how to make applesauce but orange is selected then write how to make orange?

so far I have a basic form and select options and I know how to do the document.write but I dont know how to use a select form with if else

thanks for the help

A: 

Your HTML markup

<select id="Dropdown" >
    <option value="Apple">Apple</option>
    <option value="Orange">Orange</option>
</select>

Your JavaScript logic

if(document.getElementById('Dropdown').options[document.getElementById('Dropdown').selectedIndex].value == "Apple") {
//write applesauce
}
else {
//everything else
}
Dustin Laine
I think you are mixing things. Looks like you're using jQuery-ish selector functions, but you just wrote "if('#Dropdown')".Also, use <code>===</code> where possible.
janmoesen
Sorry, fixed. When I think JavaScript I think jQuery.
Dustin Laine
A: 
var select = document.getElementById('myList');
if (select.value === 'apple') {
  /* Applesauce */
} else if (select.value === 'orange') {
  /* Orange */
}
janmoesen
+1  A: 

First, make sure you have an id on your <select> allowing you to reference it from Javascript:

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

Now, you can use the options and selectedIndex fields on the Javascript representation of your <select> to access the current selected value:

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

if (selection == "apple") {
    alert("APPLE!!!");
}
Jørn Schou-Rode
A: 

Alternatively you can do this.

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>
The Elite Gentleman