6
votes

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.

5

5 Answers

10
votes

Have you tried use handsontable('alter', 'insert_col', index, amount) method? You can add and remove columns and rows using alter method. See the documentation page of the handsontable project.

3
votes

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);
0
votes

if you define columns settings then it will not adding columns runtime to fix this please see link How to create dynamic columns for Handsontable?

0
votes

You should use alter function

Suppose you have a 2x3 Table and you want it be 5x5.

curRows = myTable.countRows() //curRows = 2
curCols = myTable.countCols() //curCols = 3
var newRows = 5
var newCols = 5

if(newRows > curRows){
   myTable.alter('insert_row',curRows ,newRows - curRows); 
}
else if (newRows < curRows){
    myTable.alter('remove_row', curRows,curRows - newRows );
}
if(newCols > curCols){
    myTable.alter('insert_col',curCols, newCols - curCols); 
}
else if (newCols < curCols){
    myTable.alter('remove_col',curCols, curCols - newCols);
}
0
votes
<div id="handsontable"></div>

JS

var Data = [{
    "header": {scope1: Name, scope2: Address, scope3: Address, scope4: Country},
    "tableData":[{....}, {....}]
}]
var $container = $('#handsontable');
var headerData = [];
var tableData = Data.tableData; 

$.each(Data.header, function(k,v){
    headerData.push(v);
});

$container.handsontable({
    colHeaders: function (col) {
        var j=0;
        var colCount = headerData.length;
        do {
            if(col == j)
                return headerData[j];
            j++;
        } while (j<colCount)
    }
});

var hot = $container.data('handsontable');
hot.loadData(tableData);