I\'m using Oleg\'s select2 demo, but I am wondering whether it would be possible to change the currently selected value in the dropdown menu.
For example, if the fou
do this
$('select#id').val(selectYear).select2();
if you have ajax data source please refer this for bugs free
https://select2.org/programmatic-control/add-select-clear-items
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
if you want to select a single value then use
$('#select').val(1).change()
if you want to select multiple values then set value in array so you can use this code
$('#select').val([1,2,3]).change()
My Expected code :
$('#my-select').val('').change();
working perfectly thank to @PanPipes for the usefull one.
Having some troubles with setting a String option selected in a select2:
With the option: "option string1 /option" used:
$('#select').val("string1").change();
BUT with an option with a value: option value "E" string1 /option :
$('#select').val("E").change(); // you must enter the Value instead of the string
Hopes this help someone struggling with the same issue.
if you want to set a selected item when you know the text from drop down list and don't know the value, here is an example:
Say you figured out a timezone and want to set it, but values has time_zone_id
in them.
var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var $select2 = $('#time-zone');
var selected = $select2.find("option:contains('"+timeZone+"')").val();
$select2.val(selected).trigger('change.select2');