Handsontable example

by Gabriel Vazquez

HTML

<h2>Rendering custom HTML in header</h2>

<p>You can also put HTML into row and column headers.</p>
<p>If you need to attach events to DOM elements like the checkbox below, just remember to identify the element by class name, not by id. This is because row and column headers are duplicated in the DOM tree and id attribute must be unique.</p>
<div id="example2" class="handsontable"></div>
<p>
    <button name="dump" data-dump="#example2" title="Prints current data source to Firebug/Chrome Dev Tools">Dump data to console</button>
</p>

CSS

</style><!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="http://handsontable.com/dist/handsontable.full.js"></script> <link rel="stylesheet" media="screen" href="http://handsontable.com/dist/handsontable.full.css"> <link rel="stylesheet" media="screen" href="http://handsontable.com/demo/css/samples.css"> <style type="text/css"> body {
    background: white;
    margin: 20px;
}
h2 {
    margin: 20px 0;
}

JavaScript

$(document).ready(function () {

    var myData = [{
        name: "Marcin",
        active: true
    }, {
        name: "Jude",
        active: false
    }, {
        name: "Zylbert",
        active: false
    }, {
        name: "Henry",
        active: false
    }]

    var $container = $("#example2");
    $container.handsontable({
        data: myData,
        columns: [{
            data: 'name'
        }, {
            type: 'checkbox',
            data: 'active'
        }],
        colHeaders: function (col) {
            switch (col) {
                case 0:
                    return "<b>Bold</b> and <em>Beautiful</em>";

                case 1:
                    var txt = "<input type='checkbox' class='checker' ";
                    txt += isChecked() ? 'checked="checked"' : '';
                    txt += "> Select all";
                    return txt;
            }
        }
    });

    $container.on('mouseup', 'input.checker', function (event) {
        var current = !$('input.checker').is(':checked'); //returns boolean
            for (var i = 0, ilen = myData.length; i < ilen; i++) {
                myData[i].active = current;
            }
        $container.handsontable('render');
    });

    function isChecked() {
        for (var i = 0, ilen = myData.length; i < ilen; i++) {
            if (!myData[i].active) {
                return false;
            }
        }
        return true;
    }

    function bindDumpButton() {
        $('body').on('click', 'button[name=dump]', function () {
            var dump = $(this).data('dump');
            var $container = $(dump);
            console.log('data of ' + dump, $container.handsontable('getData'));
        });
    }
    bindDumpButton();

});