Scott Scott - 5 months ago 8
HTML Question

Finding the selected index by getElementById isn't returning the right value

The selection of the "building" drop-down should equal zero. It is on the the first option. Function search() is executed when the button beside the drop-down is selected. For some reason the alert is returning "It didn't work."

<script>
var a = document.getElementById("building").selectedIndex;

function search() {
if (a === 0) {
window.alert("It worked.");
event.preventDefault();
} else {
window.alert("It didn't work.");
event.preventDefault();
}
}
</script>


Here is the selection drop-down.

<form id="apartmentSelection">
<br>
Building:
<select id="building">
<option value="all">All</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</form>


And here is the button.

<button onclick="search()">Search</button>

Answer

Var a is in the wrong place and you don't need event.preventDefault(); twice.

function search() {
event.preventDefault();
var a = document.getElementById("building").selectedIndex;
   if(a === 0){
   alert("It worked.");
   } else {
   alert("It didn't work.");     
   }   
}

I hope this helps. Happy coding!

Would the person who down voted like to explain the reason for the down vote? This clearly explains the issue with the OP's source and a solution is given...

Comments