DOM JS retrieving select option

Oct7
  • Share

Difficulty: ★★☆☆☆

Retrieving values from a select dropdown isn’t that easy as retrieving a value from an inputbox.
See the differences below:

<form name="theForm" method="post">
 <input name="inputBoxVal" type="text" />
 <select name="numbers">
  <option>number 1</option>
  <option>number 2</option>
 </select>
 <button type="submit">Submit</button>
</form>

Retrieving an input value:

var form = document.getElementById("theForm");
var inputBoxValue = form.inputBoxVal;

Retrieving values from a selectbox:

var form = document.getElementById("theForm");
var selects = form.getElementsByTagName('select');
        for(var i = 0; i < selects.length; i++) {
            var selection = selects[i].options[selects[i].selectedIndex].text;
        }


Leave a comment