Skip to content
Advertisement

select2 – How to change the value to the first option of the list with jQuery?

I have a form with a select2 dropdown.

The dropdown is in a “modal” window and I want to be able to reset my form when the modal is closed.

Behaviour wanted: When the modal is opened, I want the default value to be the first option in my select.

<select id="mylist">
    <option value="4">A</option>
    <option value="2">B</option>
    <option value="1">C</option>
    <option value="3">D</option>
</select>

In this case, the selected value would be A (value = 4).

Note that these values are populated dynamically and it cannot be hardcoded.

My reset function would be:

function reset() {
    $('#mylist').val( /* Code I'm looking for goes here */ );
}

Advertisement

Answer

Just after I posted my question I found something that was working with select2('val', ..) but it is deprecated in 4.0 and will be removed in 4.1.

The missing part on my end was triggering the change event… as I saw in the deprecated documentation. I added it and the event fired the value update!

Here is what finally worked:

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