Select2 is a jQuery plugin that customizes HTML select element and makes it more user-friendly.
It adds search features and allows to add an image with options.
The HTML select element option can easily set selected using jQuery – $(selector).val(option-value);
.
But this does not directly work with the Select2 dropdown element.
In this tutorial, I show how you can dynamically set an option selected in Select2 with jQuery.
Contents
1. Download & Include
- Download the Select2 plugin from here.
- Include select2.min.css, select2.min.js, along with jQuery library at the
<head>
.
<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
2. HTML
Create two <select >
with similar options.
- The first
<select>
is used to initialize select2 plugin. - The second
<select>
is used to set an option selected on the first dropdown when the option gets selected with jQuery. In this element doesn’t initialize select2.
Completed Code
<!-- Use to Initialize select2 --> <select id='sel_users'> <option value=''>-- Select User--</option> <option value='yogesh'>Yogesh Singh</option> <option value='sonarika'>Sonarika Bhadoria</option> <option value='anil'>Anil Singh</option> <option value='akilesh'>Akilesh Sahu</option> </select> <br><br> <!-- Use to set an option selected in the First dropdown --> Set selected: <select id='user_selected'> <option value=''>-- Select User--</option> <option value='yogesh'>Yogesh Singh</option> <option value='sonarika'>Sonarika Bhadoria</option> <option value='anil'>Anil Singh</option> <option value='akilesh'>Akilesh Sahu</option> </select>
3. Script
Initialize select2 on <select id='sel_users'>
.
On option change from $('#user_selected')
then get the selected value.
To set option selected in <select id='sel_users'>
pass value in val(value)
and to update the view need to call –
$('#sel_users').select2().trigger('change');
Completed Code
$(document).ready(function(){ // Initialize Select2 $('#sel_users').select2(); // Set option selected onchange $('#user_selected').change(function(){ var value = $(this).val(); // Set selected $('#sel_users').val(value); $('#sel_users').select2().trigger('change'); }); });
4. Demo
5. Conclusion
Pass value in the val()
to set the selected option with jQuery but also need to call select2().trigger('change')
on the selector to update the view.