How to add or remove options from select2 dynamically

  • admin
  • Tag 1
    Tag 2
    Tag 3
    Tag 4

    Select2 is an awesome jQuery extension, that adds a lot of functionality to simple select fields in a form. It allows ajax lazy loading options, searching within options and a lot more. While select2 is very versatile, it also can be difficult to work with. I’ve recently been working on a project that makes heavy use of the select2 library, and needed to be able to dynamically change the select options.

    After hours of searching google, as well as stack overflow, I found that a lot of people said that unless you modified the code that created the object, it was not possible to manipulate it how I wanted. Refusing to accept this, I set about trying to find a way. After many hours of hair pulling, frustration and coffee, I managed to find a solution. While it may not be the prettiest bit of code, It works. The code looks like this:

    
    var rowdata = $(".element_select_2_is_bound_to").data('select2'); 
    
    // grabs us a copy of the select2 object bound to our element.
    
    

    Awesome, now we have access to, and can manipulate the object. Let’s start by clearing all the options from it so we can start fresh. This is the part that had me stumped for the the longest time, as it was this that people said was not possible.

     
    
    while (rowdata.opts.data.length) {
        rowdata.opts.data.pop();
    
    }
    
    // clears data from object. Useful if you want to clear all options. You can also look at the rowdata.opts.data and pop off single items by index key like so
    
    rowdata.opts.data[0].pop();
    
    

    Spectacular, however this doesn’t clear the initial selected value. To do that, we can just do this:

    
    $(".element_select_2_is_bound_to").select2('val', '');
    //retarget bound element and set blank value.
    
    

    So now we can go about adding our options in.

    Notes:

  • The rowdata.opts.data is an object, containing each option like so: {id:option_id, text:’some_text’}
  • To address a single key you’d do something like: rowdata.opts.data[0].id, or rowdata.opts.data[0].text.
  • So we know that to add our options, we need to give the object values it expects. We can do this anyways we please, but for our example we’ll feed the object data from an array we have already built.

    
    // I'm using a pre-built array returned from an ajax call. It's parsed with wp_send_json(). The structure is just a nested array that looks something like this: 
    
    // array('results'=>array('data'=>array(array('id'=>'1', 'text'=>'option_1'), array('id'=>'2', 'text'=>'option_2'), array('id'=>'3', 'text'=>'option_3'))));
    
    $.each(response.results.data, function(object, value) {
        rowdata.opts.data.push({
            id : value.id,
            text : value.text
        });
    
    });
    
    

    And with that, we have successfully populated the select2 with new options dynamically.

    Leave a comment

  • (required)