Add editable column headers to handsontable

I am using Handsontable in some of my projects at work. One of the requirements I had to implement recently was the ability to enter custom header values. Fortunately the developer of Handsontable did a very good job on documentation, so it was not as hard as I thought.

First step is to define a function for the colHeaders property. The function returns the HTML code for an input element, which gets the initial value of an array that contains the original values of the data.


var colHeadings = ['', 'Maserati', 'Mazda', 'Mercedes', 'Mini', 'Mitsubishi'];
var data = [
    ['2009', 0, 2941, 4303, 354, 5814],
    ['2010', 3, 2905, 2867, 412, 5284],
    ['2011', 4, 2517, 4822, 552, 6127],
    ['2012', 2, 2422, 5399, 776, 4151]
],
container = document.getElementById('example'),
hot;

hot = new Handsontable(container, {
    data: data,
    colHeaders: function (index) {
        var textbox = '<input type="text" value="' + colHeadings[index] + '" />';
        return textbox;
    }
});

The result looks like this:
image

What I don’t like so far is the fact, that the whole column gets selected if the textbox is clicked. To deactivate this behavior I needed to implement another function for the event afterOnMouseDown inside the Handsontable constructor:


afterOnCellMouseDown : function(sender, e){
    if (e.row === -1)
    {
        this.getInstance().deselectCell();
    }
}

image

You can find the complete example on jsfiddle and play around with it: https://jsfiddle.net/q58odgke/


Kick It auf dotnet-kicks.de

4 thoughts on “Add editable column headers to handsontable

  1. This is clever but it doesn’t actually interact with handsontable’s data source or schema so it’s only changing the display of the data. If you have any code that actually interacts with the data itself it won’t work.

    • If you edit the header and then edit any of the table data, the headers revert to their original values. Probably need to listen for changes to the input boxes and store the new values in the source arrays.

      • But that results in more issues…
        (1) There are actually two overlapping copies of the table headers (ht_master and ht_clone) so you have to make sure you’re reading the value from the correct input box
        (2) For every edit to the table, the headers are apparently recreated, so you have to find a way to re-add even listeners after that point

      • After working with this for a while, I think it’s going to be easier to just use the first row of the table as the column header and change the styling to make it look like a header. Then I can take advantage of handsontable’s built-in editor and don’t have to keep working around all these obstacles.

Leave a Reply

Your email address will not be published.


*