【发布时间】:2014-12-08 12:09:19
【问题描述】:
我正在尝试设置 select2 单选下拉列表的默认值:http://ivaynberg.github.io/select2/。
我可以使用 select2 下拉菜单。但我不确定如何设置默认值。例如,假设值列表是 - test1、test2、test3。如何将“test1”设置为单选下拉菜单的默认值。
$(function(){
var testData = [{id:0, text:"test1"}, {id:1, text:"test2"}, {id:2, text:"test3"}];
$('#select2customdata').select2({placeholder:"Search Stuff", data: {results: testData, text:'text'}});
$('#select2customdata').select2().select2("val", "test1");
});
而 html 有:
<input type="hidden" id="select2customdata" style="width:300px"> </input>
如您所见,我使用 select2("val", "some-val") 来设置默认值。它对我不起作用。
编辑:我想出了解决方案,如果使用 val,则必须在选项中有 initselection。其他解决方案是使用:
$('#select2customdata').select2("data", {"id": id_val, "text": text_val})
【问题讨论】:
-
请提供一些示例代码。
-
你有一个有效的例子吗?如果你初始化它,你会丢失你可能在初始化后添加的数据(通过 JSON 请求),所以这个答案在那种情况下不起作用。
标签: python django jquery-select2