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();
});

What Do You Think?

Reader Comments

Post a Comment

Comment Etiquette:

  • 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 or appear to be advertisments, will not be published.
  • Comments that appear to be created for the purpose of linkbuilding to commercial sites will be removed.

We are all adults here so play nice.

*
*



Archives Blog Listing

Tag Listing

Learn CF In A Week

Treehouse

 
Fork me on GitHub