简体   繁体   English

select2以编程方式更改选择

[英]select2 change selection programmatically

I've got a select2 selection that I'm trying to set the value for using javascript. 我有一个select2选择,我试图设置使用javascript的值。 I've created a fiddle at this address. 我在这个地址开了个小提琴。 https://jsfiddle.net/rfeynman/wn9v3bud/ https://jsfiddle.net/rfeynman/wn9v3bud/

I'm trying both he following 我正在尝试他都跟随

// 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");

My problem is that I'm unable to change the selection for a select2 input that loads data using ajax. 我的问题是我无法更改使用ajax加载数据的select2输入的选择。 Any idea what i'm doing wrong? 知道我在做什么错吗?

looks like this can be done using the following code. 看起来可以使用以下代码完成此操作。 you need to add the option to the select list and then set the value. 您需要将该选项添加到选择列表中,然后设置值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM