Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected option to multiple list using jQuery

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.

like image 422
sealview Avatar asked Dec 06 '16 17:12

sealview


People also ask

How set multiple selected values in Dropdownlist jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.

What is MultiSelect in jQuery?

jQuery MultiSelect is a form component which allows users to select multiple items from a list of available options. Each selected item is rendered as a tag with a built-in icon to remove the value, giving users a sleek visual interface to preview their list of selected items.


1 Answers

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>
like image 151
Zakaria Acharki Avatar answered Oct 30 '22 12:10

Zakaria Acharki