jQuery: Get all Selected Values or Text from a Multiple Select Listbox CodeUnit 01 MAR 2010

Grabbing all the selected values or even text values from a multiple select listbox turns out to be quite simple if you know which tools to use.

The idea here is pretty simple. First we declare an array to hold our gleaned variables. Then we need to grab all the selected items in the listbox by making use of the :selected jQuery selector. Next we iterate through the selected items, using the standard val() to return the selected option’s value or text() to grab the actual display text that made up the list item.

Translating this all to jQuery code, we get this:

var realvalues = [];
var textvalues = [];
$('#multiplelistbox :selected').each(function(i, selected) {
    realvalues[i] = $(selected).val();
    textvalues[i] = $(selected).text();
});

And that’s pretty much it. If you check out the two arrays we just created then you’ll see we are now in possession of all selected values, as well as the selected list items’ display text.

Simple.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.