Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 set selected value new method

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?

like image 265
Lelio Faieta Avatar asked Feb 21 '15 17:02

Lelio Faieta


1 Answers

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

like image 147
James Hibbard Avatar answered Oct 22 '22 01:10

James Hibbard