12

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!

Fabian Sierra
  • 662
  • 1
  • 8
  • 19

6 Answers6

20

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

$('#mylist').val(1).trigger('change.select2');
Seva Kalashnikov
  • 3,735
  • 2
  • 13
  • 29
5

This works for me:

$('#mylist option:eq(0)').prop('selected',true);
Stephen Rauch
  • 40,722
  • 30
  • 82
  • 105
3

please try with this:

$('#yourSelect2').val($('#yourSelect2 option:eq(1)').val()).trigger('change');

the value from eq() depends of the position that you want to select

Alberto FC
  • 31
  • 1
1

It's better to use attribute specifiers and set that element's selected prop to true like so:

$('option[value="op2"]').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="list">
  <option value="op1">Option 1</option>
  <option value="op2">Option 2</option>
  <option value="op3">Option 3</option>
  <option value="op4">Option 4</option>
</select>

Then change op2 to whatever the value attribute of the desired default option is.

m_callens
  • 4,800
  • 4
  • 24
  • 42
1

Please do this

$('select#mylist').val(1).select2();
Jaskaran singh Rajal
  • 2,071
  • 2
  • 14
  • 27
0

As you may know Select2 need data in particular format only [id="id_value",text="data_linked_to_id"]

Lets consider you want to select first item ,you should have its Id which is used by select2 to list all items.(let here first id be 1)

$('#selectElementId').val("1"); $('#selectElementId').trigger('change');

If want to set multiple items selected then pass array of ids.

ids=["1","3","4"]

$("#selectElementId").val(ids);

$("#selectElementId").trigger('change');

           **OR**

$("#selectElementId").val(["1","3","4"]);

$("#selectElementId").trigger('change');

niks
  • 79
  • 2