I have a jQuery Select2 control that uses AJAX to populate:
<input type="text" name="select2" id="select2" style='width:400px' value="999">
var initialSelection = { id: '999', text:"Some initial option"};
$("#select2").select2({
placeholder: "Select Option",
minimumInputLength: 2,
ajax: {
url: "/servletToGetMyData",
dataType: 'json',
data: function (term, page) { return { term: term }; },
results: function (data, page) { return { results: data.results} }
},
initSelection : function(element, callback){ callback(initialSelection); },
escapeMarkup: function (m) { return m; }
});
The AJAX links to a database of possible options and as you can see requires two characters of input.
The problem is the user can use a dialog to add a new option if the option doesn't exist in the database. Upon return from that dialog, I try:
var o = $("<option/>", {value: newID, text: newText});
$('#select2').append(o);
$('#select2 option[value="' + newID + '"]').prop('selected',true);
$('#select2').trigger('change');
But it doesn't work. The same exact code works for non-AJAX Select2 boxes. I've tried various alternatives, like using $('#select2').select2("val", newID);
but it doesn't work.
I've even tried completely deleting the Select2 control. However, $('#select2').remove()
only removes the original <input> field but leaves the Select2 control lingering around. Note that the page has more than one Select2 control, so I can't use a class selector for Select2 controls as it will remove other controls that I need.
Any idea how to either a) dynamically add an option to a Select2 control that uses AJAX; or b) completely delete a Select2 control so that it can be programmatically added back? Or any other solution...
Edit
I found another question that shows how to remove a select2 element, using .select2("destroy"). This works but is, in my opinion, sub-optimal. I would much prefer to be able to just add the option than to destroy and re-create the select2.
See Question&Answers more detail:
os