This question asks how to get all the selected <options> of a <select> element and return their values in a comma separated list.
JQuery - Multiple Select Options
I would like to do the opposite of this question; I have a comma separated list of values for a <select> tag and would like to select each <option> whose value is in the comma separated list using jQuery.
Example Data:
<script type="text/javascript">
var data = "0a,0d,0f,0g";
</script>
<select id="ps-type" name="ps-type" multiple="multiple" size="5">
<option value="0a">Residential - Wall Insulation</option>
<option value="0b">Residential - Attic /Crawl Space Insulation</option>
<option value="0c">Residential - Foundation Insulation</option>
<option value="0d">Residential - Exterior Roof System</option>
<option value="0e">Commercial - Wall Insulation</option>
<option value="0f">Commercial - Air Barrier System (Walltite)</option>
<option value="0g">Commercial - Roof System</option>
</select>
.val() also accepts an array of values as an argument. Thus, to select multiple values, just convert your comma-separated list of values to an array, using split(","), and pass it to .val():
var data = "0a,0d,0f,0g";
$("#ps-type").val(data.split(","));
DEMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With