getElementsByClassName shows undefined value from select box

I have following code in HTML for my option list:

<p>Choose</p>
<select id="depo" value="depo" name="departs">
  <option value="IT"         name="departs" class="department">IT        </option>
  <option value="Literature" name="departs" class="department">Literature</option>
  <option value="Math"       name="departs" class="department">Math      </option>
  <option value="Biology"    name="departs" class="department">Biology   </option>
  <option value="Physics"    name="departs" class="department">Physics   </option>
</select>

<button class = "button" onclick="form_sub(); return false;">Submit</button>
<p id="show_results"></p>

And here’s JS code:

function form_sub()
{
  var d_opt = document.getElementsByClassName("department");
  var choosen_dep;
  for(var x = 0; x<d_opt.length; x++)
  {    
    if(d_opt[x] == true)
    choosen_dep = d_opt[x].value;                 
  }
  document.getElementById("show_results").innerHTML="</br>" +choosen_dep+  "</br>";
}

Every time I select any option in my select box the value returned in the code is: undefined (in the field with the paragraph with the show_results function).
Every time I select any option in my select box the value returned in the code is: undefined (in the box with the paragraph with the show_results function).
When I delete my if(d_opt[x] == true) the returned value is always equal to the last field in the select box – that is "Physics".

I do not know what the problem is – I tried these two methods but neither of them returns what I selected in the form. Does anyone have any idea what could be wrong?

8 thoughts on “getElementsByClassName shows undefined value from select box”

Leave a Comment