Scott Scott - 1 year ago 72
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."

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

function search() {
if (a === 0) {
window.alert("It worked.");
} else {
window.alert("It didn't work.");

Here is the selection drop-down.

<form id="apartmentSelection">
<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>

And here is the button.

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

Answer Source

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

function search() {
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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download