jQuery 如何在select2 jquery的标记中设置默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16994560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Default Value in tagging in select2 jquery
提问by gadss
I am using select2 (http://ivaynberg.github.io/select2/) for my tagging input. from the example in using select2 tagging the code is look like this.
我正在使用 select2 ( http://ivaynberg.github.io/select2/) 作为我的标记输入。从使用 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/中的页面示例中一样,输入的默认值是“棕色”、“红色” , & '绿色'。
回答by John S
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']);
回答by rafinskipg
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)
然后使用这 2 个函数来触发更改。(如官方文档所示)
$('.mySelect').val(['value1', 'value2']);
$('.mySelect').trigger('change.select2');
Where "value1" and "value2" are IDs of the option
elements of the select.
其中“value1”和“value2”是option
选择元素的ID 。
回答by marimaf
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,我必须将 data 属性添加到 select2 并设置值和触发更改,如下所示:
$('#mySelect').select2({
data: ['one','two'],
tags: true
});
$('#mySelect').val(['one','two']).trigger('change')