Search code examples
handsontable

add column dynamically to handsontable


I am trying to dynamically add a column to a handsontable. I don't see a sample anywhere nor o i see a method to do so in the API. Has anyone figured out a way to overcome this or have some sample code that I can look at that would help.

Thank you.


Solution

  • A temporarily solution is to maintain a data table dynamically. When a new column is required, update the data structure and reinitiate the whole table. Maybe the following snippets may be helpful to you.

    (function($) {
    $(function() {
        var data = [['a', 'b', 'c', 'd'], [1, 1, 1, 1], [2, 2, 2, 2]];
        $('#a-div').handsontable({data: data});
    
        /* add a new column */
        data[0].push('e');
        var len = data.length;
        for (var i = 1; i < len; i++) {
            data[i].push(i);
        }
        $('#a-div').handsontable({data: data});
    
        /* if new column isn't at the tail */
        data[0].splice(idx, 0, "f");
    });})(jQuery);