Select2 set selected value new method
Asked Answered
A

1

10

I use to set the default value on load for a select (using Select2) with a code like this:

$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).select2("val","<?php echo $garante; ?>");

Upgrading to version 4.0 on console I read: "Select2: The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead." So I tried to change my code to

$('#soff_gar').select2({placeholder: "Scegli", initSelection: true }).val("<?php echo $garante; ?>");

or

$('#soff_gar').select2({placeholder: "Scegli"}).val("<?php echo $garante; ?>");

but none of them works. What am I doing wrong? Any hint?

Adoration answered 21/2, 2015 at 17:59 Comment(0)
M
43

From the release notes:

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$("select").val("1"); // instead of $("select").select2("val", "1");

So, if you have a select element:

<select id="mySelect">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

In the past you would have initialised it like so:

$("#mySelect").select2().select2("val","audi");

This has been replaced with:

$("#mySelect").select2();
$("#mySelect").val("audi").trigger("change");

For you, I guess that would translate to:

$('#soff_gar').select2({
  placeholder: "Scegli", 
  initSelection: true 
});
$('#soff_gar').val(<?php echo $garante; ?>).trigger("change");

Although, is there any reason you're doing this programatically?

With reference to my example, this would also work:

<option value="audi" selected>Audi</option>

HTH

Mom answered 21/2, 2015 at 19:31 Comment(3)
So the point is on trigger("change")! Thanks! I read the notes you mention in your answer but didn't get the point. The reason for my code is on how I build the page and increase code readabilityAdoration
trigger select works but it is really trigger change event so if there is redirect after change, page will be redirect immediately. It works for me like this: $("#mySelect").val("audi").select2();Probably
<option value="audi" selected>Audi</option> works for me.Sadler

© 2022 - 2024 — McMap. All rights reserved.