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!
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.
$("#programid"). select2({ placeholder: "Select a Program", allowClear: true, minimumInputLength: 3, ajax: { url: "ajax.
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).
If you using Select2 4.x just trigger change.select2
$('#mylist').val(1).trigger('change.select2');
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