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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With