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! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • juanitogan

    Ah, it could be simpler, val() returns an array from a multiple select:
    var selectednumbers = $(“#multiselect”).val() || [];

  • You could use 

    If you send it to a server you want to uriEncode it so it doesn’t make any problems in a get request.

    Server side you have do decode it again of course.

  • Stefan

    Not necessary – $(‘#multiselect’).val() will return an array of selected values.

    • Perhaps that is the current behaviour, but this was certainly not the case when this particular code snippet was written back in 2010.

    • Alex

      Hi Stefan, I use val(), however it does not work, it returns nothing