在select2上设置标签值 [英] Set tag value on select2

查看:242
本文介绍了在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>

并且我已经为此字段初始化了select2 lib:

And I have initialized select2 lib for this field:

$("[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.

它有效.

要设置默认用户值时,请使用以下命令:

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

如何设置标签值?

推荐答案

好的,我找到了答案! 如果我们没有带有标签值的选项,则可以执行以下操作:

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.

这篇关于在select2上设置标签值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆