Gaurav Aggarwal Gaurav Aggarwal - 5 months ago 37
jQuery Question

Preloaded values in select2 where multiple select2 is initialised with same class

I am using multiple select2 on one page having

multiSelect
class on all elements and initialising select2 on all elements with one call



$('.multiSelect').select2();

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select class="multiSelect" multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>

<select class="multiSelect" multiple>
<option>First</option>
<option>Second</option>
<option>Third</option>
<option>Fourth</option>
</select>





Now i choose some values and on hit of save button all the values for each select2 get saved in database now i come on update page i want each select2 to come with values i selected.

I saw the method answered here Load values in select2 multiselect but i can't load static values i want to load the values saved in database to call according to each select2.

Answer

I found the a way for this. Rather then writing code in JS i am just adding selected attribute on the options i want to be selected by default and its working.

$('.multiSelect').select2();
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  
<select class="multiSelect" multiple>
  <option>One</option>
  <option selected>Two</option>
  <option>Three</option>
  <option>Four</option>
</select>

<select class="multiSelect" multiple>
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
  <option>Fourth</option>
</select>

The element having selected attribute will come selected by default.