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.
When working with a single select list, to get the the value of the selected option use val().
So to get the hex code stored in the selected option value of this color list we would do this.
var selectedColourHexValue = $(‘#colourSelect’).val();
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();
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.
var hexvalues = [];
var labelvalues = [];
$('#colourMultiSelect :selected').each(function(i, selectedElement) {
hexvalues[i] = $(selectedElement).val();
labelvalues[i] = $(selectedElement).text();
});