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
Just wanted to add a second answer. If you have already rendered the select as a select2, you will need to have that reflected in your selector as follows:
$("#s2id_originalSelectId").select2("val", "value to select");
For select2 version >= 4.0.0
The other solutions might not work, however the following examples should work.
$('select').val('1').trigger('change');
$('select').val('1').trigger('change.select2');
See this jsfiddle for examples of these. Thanks to @minlare for Solution 2.
Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:
$('#my-best-friend').select2();
Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:
$('#my-best-friend').val('').trigger('change');
Or say I make the system select the next in the list instead of Bob:
// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');
Notes on Select 2 website (see Deprecated and removed methods) that might be useful for others:
.select2('val') The "val" method has been deprecated and will be removed in Select2 4.1. The deprecated method no longer includes the triggerChange parameter.
You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.
$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');
You have two options - as @PanPipes answer states you can do the following.
$(element).val(val).trigger('change');
This is an acceptable solution only if one doesn't have any custom actions binded to the change event. The solution I use in this situation is to trigger a select2 specific event which updates the select2 displayed selection.
$(element).val(val).trigger('change.select2');
// 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
}
});
});
Font : Select 2 documentation