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?
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
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