Loading Select2 with a selected option WITHOUT triggering change?
Asked Answered
K

4

9

Is there any way to load select2 to a default value without triggering the change event?

Currently, I am doing:

$('#mylist').val(2).trigger("change");

But this creates a delay where the user will at first see one option and then it will change, which is quite an annoyance.

Ketty answered 13/1, 2017 at 16:39 Comment(0)
P
3

Set a default value in your HTML:

<select id="myList">
   <option id="foo">option 1</option>
   <option id="bar" selected="selected">option 2</option>
</select>

Then call select2 on your element to initialize it:

$('#myList').select2();

or

$('#myList').select2("val", null);

Paleozoic answered 13/1, 2017 at 16:45 Comment(0)
H
38

I know I'm really late to answer this question. I was facing the same issue. But doing a bit of research I found a solution that works like a charm.

You can set an option using below code

$("#mylist").val(2).trigger('change.select2');

This solution will not trigger the main change event but sets the option to the select2 component.

Hope that helps you.

Hole answered 25/10, 2019 at 11:34 Comment(3)
It does trigger change eventDiophantus
@Diophantus This triggers a change event within select2, but it will not trigger an event that was set using .on("change"). Thus, select2 will process the change, but a custom change event will not.Tilney
Exactly, the change event will be very specific to the select2 and not the main change event.Hole
S
8

If you want to set a selected option, normaly you can do:

 $('#element').val('your_val').trigger('change');

But if you dont want to run the trigger, you must to destroy it first and then assign val before create again, like this:

$('#element').select2('destroy');
$('#element').val('your_val').select2();
Suds answered 28/10, 2018 at 0:58 Comment(0)
P
3

Set a default value in your HTML:

<select id="myList">
   <option id="foo">option 1</option>
   <option id="bar" selected="selected">option 2</option>
</select>

Then call select2 on your element to initialize it:

$('#myList').select2();

or

$('#myList').select2("val", null);

Paleozoic answered 13/1, 2017 at 16:45 Comment(0)
S
0

actually the best method is using the scope of select2:

$('#mylist').val('value');
$('#mylist').trigger('change.select2');
Stodge answered 25/4, 2023 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.