Javascript Jquery选择2未显示所选值
Select2插件未显示带有templateFormat选项的选定选项 有人知道怎么修吗 标记:Javascript Jquery选择2未显示所选值,javascript,jquery-select2,select2,Javascript,Jquery Select2,Select2,Select2插件未显示带有templateFormat选项的选定选项 有人知道怎么修吗 标记: <select id="plans" style="width: 75%"> <option value="1" name="text1" price="$1" saving="text" selected="selected"></option> <option value="2" name="text2" price="$2" saving="text"
<select id="plans" style="width: 75%">
<option value="1" name="text1" price="$1" saving="text" selected="selected"></option>
<option value="2" name="text2" price="$2" saving="text" selected="selected"></option>
js:
$(文档).ready(函数(){
$(“选择计划”)。选择2({
搜索的最小结果:无穷大,
templateResult:formatState
});
});
函数格式化状态(状态){
如果(!state.id)返回state.text;
var html=''+state.element.attributes.name.value+“”
html+=''+state.element.attributes.price.value+“
html+=''+state.element.attributes.saving.value+“”
var$state=$(html);
返回$state
}
下面是上述代码的一个示例
谢谢你我想出来了。做了以下更改,它开始工作。我添加了templateSelection
$(document).ready(function(){
$('select#plans').select2(
{minimumResultsForSearch: Infinity,
templateResult: formatState,
templateSelection:formatState
});
});
解决这个问题的一个非常简单的方法是:
// Step1: Here assuming id of your selectbox is my_id, so this will add selected attribute to 1st option
$('#my_id option').eq(0).prop('selected',true);
// Step2: Now reinitialize your select box
// This will work, if you haven't initialized
selectbox $('#my_id').select2();
or
//This will work, if you have initialized selectbox earlier, so destroy it
first and initialise it
$('#my_id').select2('destroy').select2();
// Step1: Here assuming id of your selectbox is my_id, so this will add selected attribute to 1st option
$('#my_id option').eq(0).prop('selected',true);
// Step2: Now reinitialize your select box
// This will work, if you haven't initialized
selectbox $('#my_id').select2();
or
//This will work, if you have initialized selectbox earlier, so destroy it
first and initialise it
$('#my_id').select2('destroy').select2();