Reputation: 766
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!
Upvotes: 17
Views: 51767
Reputation: 239
this work for me :
$("#mylist").val($("#mylist option:first").val()).trigger('change');
juste remove -child
Upvotes: 2
Reputation: 1
Step 1: Select first option of your select(s) - works not only for select2
$('#myForm').find('select').find('option:eq(0)').attr('selected','selected');
Step 2: Trigger select2 change
$('#myForm select').trigger('change.select2');
Upvotes: 0
Reputation: 111
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');
Upvotes: 0
Reputation: 101
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
Upvotes: 10
Reputation: 81
This works for me:
$('#mylist option:eq(0)').prop('selected',true);
Upvotes: 8
Reputation: 6360
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.
Upvotes: 2
Reputation: 4392
If you using Select2 4.x just trigger change.select2
$('#mylist').val(1).trigger('change.select2');
Upvotes: 28