[英]select2 set multiple selected values
I have the following select2: 我有以下select2:
<select id="e1" multiple style="width: 250px;" name="attributes[]">
<?php if(isset($vars['attributes'])):?>
<?php foreach($vars['attributes'] as $attribute):?>
<option value="<?php echo $attribute['id'];?>"><?php echo $attribute['name'];?></option>
<?php endforeach;?>
<?php endif;?>
</select>
Now i load some of the data via. 现在我通过加载一些数据。 Ajax:
阿贾克斯:
which lists the following array: 其中列出了以下数组:
Now i wish to add these 3 as selected values to my select2. 现在,我希望将这3个选定值添加到我的select2中。
How do i do that? 我怎么做?
update 更新
HEre is my code so far: 到目前为止,这是我的代码:
var _lst = document.getElementById('e1');
var optCount = _lst.options.length;
for (var i=0 ; i<data['attributes'].length; i++){
var opt = new Option(data['attributes'][i]['name'],data['attributes'][i]['id']);
_lst.options[optCount+i] = opt;
}
A very simple way : jsFiddle example 一个非常简单的方法: jsFiddle示例
I'm not sure about your attributes
type and structure (json ? array ?) You can amend the code for your purpose. 我不确定您的
attributes
类型和结构(json?array?),您可以根据需要修改代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.