mfreitas mfreitas - 1 month ago 7x
jQuery Question

Update select2 data without rebuilding the control

I am converting an

<input type="hidden">
to a select2 dropdown and feeding it data through the query method

query: function( query ) {
query.callback( data ); // the data is in the format select2 expects and all works well..

The problem is i needed to hack the select2 UI and position two buttons on top of the search bar that, when clicked, will perform ajax calls and will have to update the select2 content.

enter image description here

Now, I need those updates to occur without rebuilding the select2 entirely but rather just refreshing the items on the dropdown. I cannot find a way to pass a new set of data to an already created select2 control, is that possible ?


If you have local array with options (recieved by ajax call), i think you should use data parameter as function returning results for select box:

var pills = [{id:0, text: "red"}, {id:1, text: "blue"}]; 

    placeholder: "Select a pill",
    data: function() { return {results: pills}; }

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
$('#newresults').click(function() {
    pills = [{id:0, text: "white"}, {id:1, text: "black"}];


In case if you customize select2 interface with buttons, just call updateResults (this method not allowed to call from outsite of select2 object but you can add it to allowedMethods array in select2 if you need to) method after updateting data array(pills in example).