jQuery and AJAX: How To Send All Selected Values from a Multiple Select Box CodeUnit 28 JUN 2010

Multi-select boxes are wonderful creatures in that they provide a particularly easy to implement user interface element that provides a great deal of functionality to the end user. Today’s quick code tip looks at how one would send all user’s selections made in a multiple select box to a processing script using a jQuery AJAX call.

First off, let us set up our multi select box:

Right. So now we have our multiple select box and a button on which to act upon. The next step is of course the meat of this quick code tutorial, looking at how to post that selected data along to a handler script using a jQuery AJAX call.

So here goes:

//run on save numbers button clicked
    //only do something if numbers are selected
    if( $('#multiselect :selected').length > 0){
        //build an array of selected values
        var selectednumbers = [];
        $('#multiselect :selected').each(function(i, selected) {
            selectednumbers[i] = $(selected).val();
        //post data to handler script. note the JSON.stringify call
            url: 'my_handler_script.php',
            data: {'selectednumbers':JSON.stringify(selectednumbers)},
            type: 'POST',
            success: function(data) {

The trick here is to remember that you can’t simply call .val() on the select box as that will only return one value and not all selected values. So we first run through the list of all selected values (returned by the handy :selected jQuery selector) and push them into a single data array.

Using the JSON2 library to return a usable JSON string of that array, we then make use of jQuery’s built in AJAX functionality to post our data off to our handler script.

And that’s it, couldn’t be simpler – we have now managed to successfully send off an array of all selected values in a multiple select box to our handler script for consumption! :)

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.