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, ...
Something like this should do the trick:
The most simple solution
You could simply use just
.val()
like :On a multiple select element, the
val
command of theselect
element will return an array of the selected options values. If no values are present, the text of the element is used:update: However, when there are no selected options
val()
returnsnull
not an empty array. One way to get around this:You can play around with it in this demo I put together.
From the docs:
You can use the
:selected
selector, and the inline$.map()
function as part of your chain.Here you go: