Tag Archives: html select

Get the text or value of a HTML select option using jQuery

Short and sweet.  How to grab the value of an element using jQuery.

If you have the element shown below, for example.

<select id="selectFruit">
    <option value="1">Orange</option>
    <option value="2">Apple</option>
    <option value="3">Bannana</option>
    <option value="4">Peach</option>
    <option value="5">Grape</option>
</select>

There are two parts to this that can be grabbed using jQuery.

To assign the “value” of the selected option to the variable “fruit” (for example):

var fruit = $("#selectFruit").val();

To assign the text element of the selected option:

var fruit = $("#selectFruit option:selected").text();

This is really handy with a change function so that the selected option can be grabbed when the status of the selector changes:

$("#selectFruit").on("change", function(){
  var fruit = $(this).val();
  // Do something with your newly assigned fruit variable
});

Just as an aside, you see that we have used “this” instead of telling jQuery which element we are talking about.  Because the value we are assigning is within the change function on the selectFruit element already, we can just refer to it within the function as “this”.

So this (pardon the pun):

var fruit = $(this).val();

Works as though we have written this:

var fruit = $("#selectFruit").val();

Within the context of this particular change function, on this particular element.

 

Share this post:
read more