Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Multiple <options> with jQuery

Tags:

html

jquery

dom

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>
like image 423
recursion.ninja Avatar asked Feb 19 '23 03:02

recursion.ninja


1 Answers

.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.

like image 123
João Silva Avatar answered Mar 04 '23 05:03

João Silva