Search code examples
javascriptjqueryhandsontable

Getting rid of TypeError while initializing HandsOntable


I am checking Handsontable for developers for one of my project. I have tried to initialize a handsontable object by following their tutorial. But i am continuously getting a TypeError.

My code is below -

var data = [
   ["","Ford","Volvo","Toyota","Honda"],
   ["2016", 10, 11, 12, 13],
   ["2017", 20, 11, 14, 13],
   ["2018", 30, 15, 12, 13]
];

var container = $("#example");
var hot = new Handsontable(container, {
   data: data,
   rowHeaders: true,
   colHeaders: true
});
<link href="http://docs.handsontable.com/0.25.0/bower_components/handsontable/dist/handsontable.full.css" rel="stylesheet"/>
<script src="http://docs.handsontable.com/0.25.0/bower_components/handsontable/dist/handsontable.full.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>

<div id="example"></div>

Demo - https://jsfiddle.net/x1w95ndx/

I have been trying to find the solution for last one hour. It will be really helpful for me if anyone show me the right direction.


Solution

  • The problem is you are passing a jQuery collection (an array-like object which can contain multiple elements and offers those jQuery methods like .css and .attr) to the Handsontable constructor, when it expects a plain DOM element.

    Replace:

    var container = $("#example");
    

    With:

    var container = $("#example")[0];
    

    Or:

    var container = document.getElementById("example");
    

    Working Example:

    var data = [
       ["","Ford","Volvo","Toyota","Honda"],
       ["2016", 10, 11, 12, 13],
       ["2017", 20, 11, 14, 13],
       ["2018", 30, 15, 12, 13]
    ];
    
    var container = $("#example")[0];
    var hot = new Handsontable(container, {
       data: data,
       rowHeaders: true,
       colHeaders: true
    });
    <link href="http://docs.handsontable.com/0.25.0/bower_components/handsontable/dist/handsontable.full.css" rel="stylesheet"/>
    <script src="http://docs.handsontable.com/0.25.0/bower_components/handsontable/dist/handsontable.full.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
    
    <div id="example"></div>