Javascript 选择2以编程方式更改选择

Javascript 选择2以编程方式更改选择,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我有一个select2选择,我正试图为使用javascript设置值。 我在这个地址做了一把小提琴。 我正试着让他跟着我 // method 1 $('#groupList').select2('data',{id:"group2", text:"group2"},true); // method 2: as seen on the select2 website var groupList = $('#groupList').select2(); $(groupList).val("gro

我有一个select2选择,我正试图为使用javascript设置值。 我在这个地址做了一把小提琴。

我正试着让他跟着我

// 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输入的选择。知道我做错了什么吗?

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

var option=$("<option>").attr("value","group2").html("group2");
$("#groupList").append(option);
$("#groupList").val("group2").trigger("change");
var option=$(“”).attr(“value”,“group2”).html(“group2”);
$(“#组列表”)。附加(可选);
$(“#组列表”).val(“组2”).trigger(“更改”);

还有另一种方法,你可以做
$(“#groupList”).select2().select2('val',value)这通常有效,但在您的案例中不起作用。这可能是因为使用了
数据
属性