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

12,648

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');
Share:
12,648
Maxime
Author by

Maxime

Hey! My name is Maxime and I am an entrepreneur, programmer and code lover. I help businesses as a technology strategist to automate their processes to increase their productivity and efficiency. I am a WordPress expert and co-founder of SatelliteWP, a WordPress service where we focus on maintenance, performance and security. I own a company called S2B Solution where we are experts in process reengineering, task automation and custom software development in complex scenarios. We develop innovative solutions designed specifically for the needs of our customers to maximize their productivity in their business process. I also blog, in French, on my personal website: www.maximejobin.com.

Updated on June 28, 2022

Comments

  • Maxime
    Maxime almost 2 years

    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 */ );
    }
    
  • Maxime
    Maxime over 7 years
    @downvoter : Can you explain why you did downvote? Maybe the answer could be improved?!
  • Mohammad Reza Shahrestani
    Mohammad Reza Shahrestani almost 5 years
    Cool and easy as pie. Thanks
  • Maxime
    Maxime almost 5 years
    How is pie "easy"? ;-)
  • Mohammad Reza Shahrestani
    Mohammad Reza Shahrestani almost 5 years
    eating that is easy :))