Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 201
Anastasiia Avatar asked Oct 29 '25 13:10

Anastasiia


1 Answers

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.

like image 124
Anastasiia Avatar answered Oct 31 '25 03:10

Anastasiia