Search code examples
javascriptjqueryjquery-select2handsontable

Handsontable Select2 Dynamic Options


I am using handsontable with the select2 editor but I cannot seem to make dynamic options work with the dropdown menu, i.e. the options set at the the time of the handsontable initialisation are the only options that ever seem to show.

I have tried using a global variable as the source of the options and updating that at various points in my code and also using a function to return the same variable but neither attempt seems to work.

e.g.

var hot;
var data = [];

function customDropdownRenderer(instance, td, row, col, prop, value, cellProperties) {

    if (instance.getCell(row, col)) {
        $(instance.getCell(row,col)).addClass('select2dropdown');
    }

    var selectedId;

    var colOptions = cellProperties.select2Options.data;

    if (colOptions != undefined) {

        for (var index = 0; index < colOptions.length; index++) {
            if (parseInt(value) === colOptions[index].id) {
                selectedId = colOptions[index].id;
                value = colOptions[index].text;            
            }
        }

        Handsontable.TextCell.renderer.apply(this, arguments);
    }
}

var  requiredText = /([^\s])/;

$(document).ready(function(){

    var
      $container = $("#example1"),
      $parent = $container.parent(),
      autosaveNotification;


    hot = new Handsontable($container[0], {
        columnSorting: true,
        stretchH: 'all',
        startRows: 8,
        startCols: 5,
        rowHeaders: true,
        colHeaders: ['Description', 'Cost', 'Remarks'],
        columns: [
            { data: 'description' },
            { 
                data: 'cost',
                editor: 'select2',
                renderer: customDropdownRenderer,
                select2Options: { data: getData(), dropdownAutoWidth: true }
            },
            { data: 'remarks' },
        ],
        minSpareCols: 0,
        minSpareRows: 1,
        contextMenu: true,
        data: []
    });

    data = [{id:'fixed',text:'Fixed'},{id:'variable',text:'Variable'}];
});

function getData() {
    return data;
}

http://jsfiddle.net/zfmdu4wt/27/


Solution

  • You have defined data multiple times and it is causing contention.

    The following changes will fix it:

    Define the following immediately after the .ready() function:

    var source = [{id:'fixed',text:'Fixed'},{id:'variable',text:'Variable'}];

    and update the select2Options to the following:

    select2Options : { data: source, dropdownAutoWidth: true }