Set selected option to multiple list using jQuery
Asked Answered
D

2

5

I have a list from DB which is displayed in select multiple tags:

<select multiple="multiple" id="list" name="color">
  <option value="1">Red</option>
  <option value="2">Green</option>
  <option value="3">Blue</option>
  <option value="4">Magenta</option>
  <option value="5">Black</option>
  <option value="6">Cyan</option>
  <option value="7">Yellow</option>
</select>

Given an array of values from DB, need to select only those items that are found in the DB array, for example [2,4,7]. How do I push, with jQuery, attr('selected') to these option tags?

<select multiple="multiple" id="list" name="color">
  <option value="1">Red</option>
  <option value="2" selected="selected">Green</option>
  <option value="3">Blue</option>
  <option value="4" selected="selected">Magenta</option>
  <option value="5">Black</option>
  <option value="6">Cyan</option>
  <option value="7" selected="selected">Yellow</option>
</select>

Like above.

Detonation answered 6/12, 2016 at 17:0 Comment(0)
I
9

You've just to use the .val() method to achieve that :

$('#list').val([2,4,7]);

$('#list').val([2,4,7]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" id="list" name="color">
  <option value="1">Red</option>
  <option value="2">Green</option>
  <option value="3">Blue</option>
  <option value="4">Magenta</option>
  <option value="5">Black</option>
  <option value="6">Cyan</option>
  <option value="7">Yellow</option>
</select>
Induct answered 6/12, 2016 at 17:2 Comment(1)
I didn't know val() took an array. Nice answer.Industrials
S
2

For the sake of completeness, I thought I would add a plain javascript solution.

Here's what I came up with, using an array, a loop, document.querySelector and setAttribute:

var preSelected = [2,4,7];

for (var i = 0; i < preSelected.length; i++) {
var option = document.querySelector('#list option[value="' + preSelected[i] + '"]');
option.setAttribute('selected','selected');
}
<select multiple="multiple" id="list" name="color">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
<option value="4">Magenta</option>
<option value="5">Black</option>
<option value="6">Cyan</option>
<option value="7">Yellow</option>
</select>
Signpost answered 6/12, 2016 at 17:20 Comment(1)
I really don't get it where I'm doing wrong... jsfiddle.net/sealview/49drqsse/1Detonation

© 2022 - 2024 — McMap. All rights reserved.