【问题标题】:Select2, set default value for Single Select Drop downSelect2,为单选下拉设置默认值
【发布时间】: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


【解决方案1】:

基于documentval:

获取或设置选择。如果不指定 value 参数,则返回当前选中元素的 id 属性。如果指定了 value 参数,它将成为当前选择。

但请注意来自doc的通知:

请注意,为了使用此方法,您必须在选项中定义 initSelection 函数,以便 Select2 知道如何将您在 val() 中传递的对象的 id 转换为呈现选择所需的完整对象。如果您要附加到选择元素,则该功能已经为您提供。

看看this post。

【讨论】:

  • 我接受了你的回答,因为你帮助我弄清楚我到底错过了什么。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-05-25
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 2019-12-28
  • 1970-01-01
  • 2014-08-25
相关资源
最近更新 更多