Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 341
Fabian Sierra Avatar asked Mar 09 '17 18:03

Fabian Sierra


People also ask

How do I stop Select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

How do I set Select2 values?

$("#programid"). select2({ placeholder: "Select a Program", allowClear: true, minimumInputLength: 3, ajax: { url: "ajax.

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).


1 Answers

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

$('#mylist').val(1).trigger('change.select2');
like image 183
Seva Kalashnikov Avatar answered Oct 05 '22 14:10

Seva Kalashnikov