Get Selected Value(s) From An Option List With JQuery

Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Working with select lists is super easy with JQuery. This is really more of a reminder for myself as I always have to look this up when I have to work with multi-select lists and JQuery.

Get Selected Option Value

When working with a single select list, to get the the value of the selected option use val().

<select name="colours" id="colourSelect">
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</select>

So to get the hex code stored in the selected option value of this color list we would do this.

var selectedColourHexValue = $(‘#colourSelect’).val();

Get Selected Option Text

If however we want the text label for the selected colour then we need to do a little more work.

First, we get the selected option with :selected selector. Then we get the text with the text() function.

var selectedColourLabel = $(‘#colourSelect :selected’).text();

Multiple Selected Values

To work with multi-select lists we use the each() function to iterate over the selected options. In the below example I build two arrays, one containing the selected hex values and the other containing the labels.

<select name="colours" id="colourMultiSelect" multiple="multiple">
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</select>
var hexvalues = [];
var labelvalues = [];

$('#colourMultiSelect :selected').each(function(i, selectedElement) {
hexvalues[i] = $(selectedElement).val();
labelvalues[i] = $(selectedElement).text();
});

Reader Comments

haz's Gravatar
haz
Tuesday, August 14, 2018 at 4:33:08 AM Coordinated Universal Time

I want to get value from two sided multi select, already follow your code but there is no data inside that array when i use console. can you help me? jQuery(document).ready(function($) { var hexvalues = []; $('#multiselect').multiselect(); $('#mltiselect :selected').each(function(i, choice_jk) { hexvalues[i] = $(choice_jk).val(); labelvalues[i] = $(choice_jk).text(); }); console.log(hexvalues); });

Steven Neiland's Gravatar
Steven Neiland
Saturday, February 2, 2019 at 12:41:59 AM Coordinated Universal Time

Haz,<br/> This is just a sample, you need to wrap this in an event. For example listen for a change or click event on the multiselect to then run this code.

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing