select2以编程方式更改选择

时间:2016-01-13 07:50:53

标签: javascript jquery jquery-select2

我有一个select2选项,我正在尝试设置使用javascript的值。 我在这个地址创造了一个小提琴。 https://jsfiddle.net/rfeynman/wn9v3bud/

我正在尝试他跟随

// method 1
$('#groupList').select2('data',{id:"group2", text:"group2"},true);

// method 2: as seen on the select2 website
var groupList = $('#groupList').select2();
$(groupList).val("group2").trigger("change");

我的问题是我无法更改使用ajax加载数据的select2输入的选择。知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

看起来可以使用以下代码完成此操作。您需要将选项添加到选择列表,然后设置值。

var option=$("<option>").attr("value","group2").html("group2");
$("#groupList").append(option);
$("#groupList").val("group2").trigger("change");
相关问题