Search code examples
javascriptjqueryjquery-select2

Set the first option select2


I want to set the first position to select2 dropdown by default, I have tried this but It doens´t work:

$('#mylist').val($('#mylist option:first-child').val()).trigger('change');

Other way that I tried;

$('#mylist').val(1);

But the problem is I don´t know what value is, because it is depend from a query and It will not always be the same value.

I did not set the dropdown values ​​from the HTML, but it is an input hidden and the values ​​are loaded in a query

I hope that anyone can help me

Regards!


Solution

  • If you using Select2 4.x just trigger change.select2

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