user1430949
user1430949

Reputation: 859

Post values from a multiple select

How can I post values from a multiple select in a form? When I hit submit none of the selected values are posted.

<form id="form" action="" method="post">
    <div>
        <select id="inscompSelected" multiple="multiple" class="lstSelected">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>                
        </select>
        <input type="submit" value="submit">
    </div>
</form>

Upvotes: 76

Views: 132263

Answers (3)

Matt Ault
Matt Ault

Reputation: 31

The route I'm about to take is to add a hidden field in the form, and modify its value using a similar algorithm to @Chin2 's above in the onchange event of the multiple select element. Then maybe remove the name field from the select element.

function selChangedEventHandler()
{
    select = document.getElementById("multiselect_id");
   
    options = select.options,
    len = options.length,
    data='',
    i=0;
    first = true;
    while ( i < len )
    {
        if (options[i].selected)
        {
            if ( !first )
            {
                data += '+';
            }
            data += options[i].value;
            first = false;
        }
        i++;
    }
    hidden = document.getElementById('hiddentext_id');
    hidden.value = data;
} 

Upvotes: 0

iambriansreed
iambriansreed

Reputation: 22241

You need to add a name attribute.

Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3.

In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.

Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs

For PHP you can use:

<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">

Upvotes: 149

Chin2
Chin2

Reputation: 53

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

Upvotes: 1

Related Questions