1

Below is my code. I want the div to appear when it is selected, however, when I press submit, the word undefined appears instead of the words I want it to be.

When I use = instead of ==, e.g. if(age="toddlers"), the sentence "Bring to picnic" appears for all selected options.

Hence, I'm suspecting that it's because I'm not reading the value correctly. I tried

if (document.getElementsByTagName('option') == "toodlers")

and it's totally not working. I just started learning HTML, CSS and JS. I tried googling for a few hours and I still cannot fix it.

<form name="outing">
<select id="outing">
<option value="toddlers">Toddlers</option>
<option value="children">Children</option>
<option value="teenagers">Teenagers</option>
<option value="adults">Adults</option>
<option value="eldery">Elderly</option>
</select>
<input type="button" name="button" value="Go!" onClick="familyOuting();">
<input type="reset" value="Reset" onClick="window.location.reload()"/>
</form>

<script type="text/javascript">
    function familyOuting(){
        var age = document.getElementById("outing").selectedIndex;
        if(age=="toddlers"){
            var place = "Bring to picnic";
        }
        if(age=="children"){
            var place = "Bring to playground";
        }
        if(age=="teenagers"){
            var place = "Bring to swimming pool";
        }
        if(age=="adults"){
            var place = "Bring to dinner";
        }
        if(age=="elderly"){
            var place = "Bring to picnic";
        }
        document.getElementById("xxx").innerHTML=(place);
    }
</script>
<div id="xxx">
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

2

selectedIndex just returns an integer, hence it will never match your string,

Instead use value...

var age = document.getElementById("outing").value;

Also, in your comparison, use === for strict comparison of strings..

if(age==="toddlers"){
    var place = "Bring to picnic";
}
Kylie
  • 11,421
  • 11
  • 47
  • 78
0
<select id="mySelect">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>

var x = document.getElementById("mySelect");
x.options[x.selectedIndex].value
v2b
  • 1,436
  • 9
  • 15