space_food_
space_food_

Reputation: 830

Loading Select2 with a selected option WITHOUT triggering change?

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.

Upvotes: 9

Views: 23497

Answers (4)

actually the best method is using the scope of select2:

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

Upvotes: 0

BEingprabhU
BEingprabhU

Reputation: 1686

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.

Upvotes: 39

nicpas
nicpas

Reputation: 101

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();

Upvotes: 9

Pabs123
Pabs123

Reputation: 3435

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);

Upvotes: 3

Related Questions