I am trying to grab all selected items in the following select multiple and separate them by a comma. The code is below:
On a multiple select element, the val
command of the select
element will return an array of the selected options values. If no values are present, the text of the element is used:
var output = $("#ps-type").val().join(', ');
update: However, when there are no selected options val()
returns null
not an empty array. One way to get around this:
var output = ($("#ps-type").val() || []).join(', ');
You can play around with it in this demo I put together.
From the docs:
In the case of
elements, the
.val()
method returns an array containing each selected option.