0

I use select2 to (https://select2.github.io) to bulding drop down list. I have problem with display selected item after refresh the page (my select is stored in DB). Where excalcly have I add select or selected="selected" ? I can't add this in because every user of my website selects own item in his settings.

<script>
$(document).ready(function() {
$(".js-example-basic-single").select2({
});
$("select").select2({
});
});          
</script>
<select class="js-example-basic-single" name="field">
  <option value="city1">city1</option>
   <option value="city2">city2</option>
</select> 

1 Answers1

-1
<script>
$(document).ready(function() {
  var storedValue = 'city2';
  var $select = $(".js-example-basic-single").select2({});
  $select.select2('val', 'storedValue');
});          
</script>
<select class="js-example-basic-single" name="field">
  <option value="city1">city1</option>
   <option value="city2">city2</option>
</select>

How you get the stored value from your server is up to you / stack. If you don't have a backend you can use localStorage to store what the user selected.

devkaoru
  • 1,142
  • 9
  • 7