简体   繁体   中英

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 */ );
}

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');

By using the "show.bs.modal" event and the .prop() method in jQuery we can do this easily.

$("#my-modal").on("show.bs.modal", function() {

    $(this).find("select option:eq(0)").prop("selected", true);

});

This would fire every time the modal is opened and because we're using "show.bs.modal" instead of "shown.bs.modal" you shouldn't even see the selection being changed.

For all select2 in form:

$('#formId select').each( function( key, value ) {
  $(this).val($(this).find('option:first-child').val()).trigger('change');
});

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');

In your specific case:

$('#mylist').find('option:eq(0)').attr('selected','selected');
$('#mylist select').trigger('change.select2');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM