Search code examples
javascripthtmlformsselectgetelementsbyclassname

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?


Solution

  • Every one of your d_opt[x] values is always going to be an HTMLOptionElement object, not a boolean. It makes no sense to compare them to true.

    To get the selected option, read the value of the select element.

    function form_sub() {
    
      var d_select = document.getElementById("depo");
      document.getElementById("show_results").innerHTML = "<br>" + d_select.value + "<br>";
    
    }
    <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>

    Also note that the start tag for the br element is mandatory but the end tag is forbidden. You are trying to insert end tags without start tags.