Search code examples
javascriptjquerycsstwitter-bootstraphandsontable

Using HandsonTable in Bootstrap Modal doesn't work


I'm trying to make use of this jquery plugin so I can have Excel-like cells on my website. However I'm using it with a modal as part of creating a new activity for an overview and that doesn't work quite as expected.

For one, the cell is not rendered correctly until the modal is closed and re-opened and when I try to destroy the cells after closing the modal so I can re-add them blank, it doesn't remove the old cells but just adds a new set underneath.

I deduce that this is because the modal is hidden initially, so the library can't render the cells right. Because I tried to put it on a blank website where it worked just fine. So I tried to add the cells after the modal is ready but that still doesn't work right.

function CreateHandsonTable() {
    $('#new-activity-modal').on('shown.bs.modal', function (e) {
        var data = [['Column A', 'Column B', 'Column C'], ['1', '2', '3']];
        var container = document.getElementById("example");
        hot = new Handsontable(container, {
            data: data
        });
    });
    $('#new-activity-modal').on('hidden.bs.modal', function (e) {
        hot.destroy();
    });
}

I use the above to create the cells, and this is what I got:

enter image description here

You can see that the picture stretches way beyond what it's supposed to hold in the three cells. Now if I make the modal lose focus or close it, I get this:

enter image description here

And a little further down I get this:

enter image description here

So clearly it has to do with the fact that I want to use the cells with an initially hidden element and probably also using the plugin wrong due to the fact that I can't even delete the previous set of cells.

Any help is appreciated :)

I made a jsfiddle to help out.


Solution

  • Playing with your fiddle changing hidden to hide seemed to fix the replication issue:

    function CreateHandsonTable() {
        $('#new-activity-modal').on('shown.bs.modal', function (e) {
            var data = [['Column A', 'Column B', 'Column C'], ['1', '2', '3']];
            var container = document.getElementById("example");
            hot = new Handsontable(container, {
                data: data
            });
        });
        $('#new-activity-modal').on('hide.bs.modal', function (e) {
            hot.destroy();
        });
    }