简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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