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>
<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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.