简体   繁体   English

如何在select2 jquery中设置标记中的默认值

[英]How to set Default Value in tagging in select2 jquery

I am using select2 ( http://ivaynberg.github.io/select2/ ) for my tagging input. 我使用select2( http://ivaynberg.github.io/select2/ )作为我的标记输入。 from the example in using select2 tagging the code is look like this. 从使用select2标记的示例来看,代码看起来像这样。

 $("#e12").select2({tags:["red", "green", "blue"]});

now my problem is how can I insert default value in my input just like in the page example in http://ivaynberg.github.io/select2/ at Tagging Support, the input has a default value of 'brown', 'red', & 'green'. 现在我的问题是如何在我的输入中插入默认值,就像在http://ivaynberg.github.io/select2/的标记支持中的页面示例中一样,输入的默认值为'brown','red' , & '绿色'。

You can initialize the Select2 control by providing a value for the hidden input: 您可以通过为隐藏输入提供值来初始化Select2控件:

<input type="hidden" id="e12" value="brown,red,green" />

And you can set the value of the Select2 control by passing an array to the 'val' method: 您可以通过将数组传递给'val'方法来设置Select2控件的值:

$('#tagSelect').select2('val', ['brown','red','green']);

jsfiddle demo jsfiddle演示

Updated version 更新后的版本

Say you initialized your select like this: 假设你初始化你的选择如下:

$('.mySelect').select2({
  multiple: true,
  tags: "true"
});

Then use this 2 functions for triggering the change. 然后使用这两个函数来触发更改。 (as seen in the official documentation) (如官方文档中所示)

$('.mySelect').val(['value1', 'value2']);
$('.mySelect').trigger('change.select2');

Where "value1" and "value2" are IDs of the option elements of the select. 其中“value1”和“value2”是select的option元素的ID。

For Select2 4.0 I had to add the data attribute to select2 and also set value and trigger change, like this: 对于Select2 4.0,我必须将数据属性添加到select2,并设置值和触发器更改,如下所示:

$('#mySelect').select2({
  data: ['one','two'],
  tags: true
});
$('#mySelect').val(['one','two']).trigger('change')

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

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