[英]Set tag value on select2
I have select field on my page: 我的页面上有选择字段:
<label>
<span>Select name</span>
<select name="name">
<option value="Option1">Option 1</option>
<option value="Option2">Option 2</option>
</select>
</label>
And I have initialized select2 lib for this field: 我已经为此字段初始化了select2 lib:
$("[name='name']").select2({
allowClear: true,
tags: true
});
As you can see I need to use tags because user can write an option, not included in the proposed. 如您所见,我需要使用标签,因为用户可以编写一个建议中未包含的选项。
And it works. 而且有效。
When I want to set the default user value I use this command: 当我要设置默认用户值时,请使用以下命令:
$("[name='name']").val(Option1).trigger("change");
And it works if the value is one of the select options values. 如果该值是选择选项值之一,则它可以工作。 But if I want set other value, the tag doesn't set.
但是,如果要设置其他值,则不会设置标签。
$("[name='name']").val(Option3).trigger("change");
What can I do to set tag value? 如何设置标签值?
ok, I found the answer! 好的,我找到了答案! If we don't have an option with tag value, we just do something like this:
如果我们没有带有标签值的选项,则只需执行以下操作:
var tagValue = [{id: Option3, text: Option3}];
$("[name='name']").select2({
allowClear: true,
tags: true,
data: tagValue
});
$("[name='name']").val(tagValue).trigger('change');
So, the first part of this code makes an additional option in our select and after that we can use it as value to set it. 因此,此代码的第一部分在我们的选择中添加了一个附加选项,之后我们可以将其用作设置它的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.