[英]Cannot show option selected with templateResult select2
function formatCountry(country) {
if (!country.id) {
return country.text;
}
var $country = $(
'<span class="flag-icon flag-icon-' + country.id.toLowerCase() + ' flag-icon-squared"></span>' +
'<span class="flag-text">' + country.text + "</span>"
);
return $country;
};
$("[name='country']").select2({
templateResult: formatCountry,
data: isoCountries
});
I use this code for country select, but when I refresh page, option selected return dafault value. 我使用此代码进行国家/地区选择,但是当我刷新页面时,选择的选项会返回dafault值。
You can use local storage like this. 您可以像这样使用本地存储。
$("[name='country']").select2({
placeholder: "Select a country",
templateResult: formatCountry,
data: isoCountries
});
var OldValue = localStorage.getItem("Key");
if (OldValue !== "" && OldValue !== null) {
$('select').select2({
placeholder: "Select a country",
templateResult: formatCountry,
data: isoCountries
}).select2('val', OldValue);
}
$("[name='country']").on("change", function() {
var selected = $(this).val();
localStorage.setItem("Key", selected);
});
Run fiddle multi-pal time and you can see the result. 运行多朋友的小提琴时间,您可以看到结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.