Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Multiple Select Options

Tags:

jquery

select

I am trying to grab all selected items in the following select multiple and separate them by a comma. The code is below:

<select id="ps-type" name="ps-type" multiple="multiple" size="5">     <option>Residential - Wall Insulation</option>     <option>Residential - Attic /Crawl Space Insulation</option>     <option>Residential - Foundation Insulation</option>     <option>Residential - Exterior Roof System</option>     <option>Commercial - Wall Insulation</option>     <option>Commercial - Air Barrier System (Walltite)</option>     <option>Commercial - Roof System</option> </select> 

The result I am looking for is the following:

Residential - Wall Insulation, Commercial - Wall Insulation, ...

like image 779
Brad Birdsall Avatar asked Feb 18 '10 16:02

Brad Birdsall


People also ask

How can I get multiple selected values of select box in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.

How do you select multiple selection options?

Selecting multiple options vary in different operating systems and browsers: For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

What is Multiselect in jQuery?

multiSelect is a jQuery plugin for converting an DIV element into a select list which allows you to select multiple items from a dropdown list as like a tag/token input.


2 Answers

You can use the :selected selector, and the inline $.map() function as part of your chain.

$("option:selected").map(function(){ return this.value }).get().join(", "); 
like image 96
Sampson Avatar answered Sep 25 '22 01:09

Sampson


Add the values to an array and use join to create the string:

var items = []; $('#ps-type option:selected').each(function(){ items.push($(this).val()); }); var result = items.join(', '); 
like image 20
Guffa Avatar answered Sep 22 '22 01:09

Guffa