Set tag value on select2

夙愿已清 提交于 2019-12-12 04:26:26

问题


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:

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


回答1:


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.



来源:https://stackoverflow.com/questions/38767515/set-tag-value-on-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!