Get the value of a select dropdown using jQuery or JavaScript

print
Sometimes you just need to grab the value of the selected option with Javascript, or jQuery, if that is your flavour.

Something to bear in mind that confuses some people, is that the select options have two parts.  One of those parts is the value, as selected in the value=”” section, and the other is the text value that is displayed on the users browser.

Here’s how to get either the hidden value, or the text value with either method:

Good old JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery:

$("#elementId :selected").text(); 
$("#elementId").val();

The element ID refers to the id of the selector, for example:

<select name="someName" id="elementID">
  <option value="[VALUE]">[TEXT]</option>
</select>

 

Share this post:
Related Posts
Stop jQuery ignoring the if/else conditions
Getting the value or text of an HTML attribute using jQuery

Leave a Comment