Reed Armstrong
Reed Armstrong

Reputation: 65

Add multi select values from drop down list to an Array

I am trying to grab selected values from a multi select drop down, and add the selected values to an Array.

The way I currently have it, it adds all of the values in the drop down, rather than the selected values.

Here is the HTML:

<div class="form-group">
    <select multiple class="form-control" id="servicePackageTypeText">
        <option disabled selected value> -- select an option -- </option>
        <option><?php echo $servicehtml ?></option>
    </select>
</div>

Here is the JavaScript:

var sourcetype = document.getElementById("servicePackageTypeText"); 
var servicearray = new Array();

for (i = 0; i < sourcetype.length; i++) 
{ 
    servicearray.push(sourcetype.options[i].value);
}

Any tips on how to grab the selected values? Thank you.

Upvotes: 0

Views: 40

Answers (1)

Reed Armstrong
Reed Armstrong

Reputation: 65

I was able to solve this using "selectOptions" in my for loop:

var sourcetype = document.getElementById("servicePackageTypeText"); 
var servicearray = new Array();
for (i = 0; i < sourcetype.selectedOptions.length; i++) 
{ 
    servicearray.push(sourcetype.selectedOptions[i].value);
}

Upvotes: 2

Related Questions