3

I'm trying to add data to a table dynamically through JavaScript, and it returns this:

Uncaught TypeError: Cannot read property 'add' of undefined.

EDIT: The code works perfectly without the row.add line.

Relevant code:

<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/jquery.dataTables.min.css">

<script type="text/javascript" src="./lib/jquery.min.js"></script>
<script type="text/javascript" src="./lib/jquery.dataTables.min.js"></script>

<script>
var dataSet = [
    ['1.1','2.1'],
    ['1.2','2.2'],
];

$(document).ready(function() {
    $('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
    t = $('#example').dataTable( 
    {
        data: dataSet,
        columns: [
            { "title": "Col 1" },
            { "title": "Col 2" },
        ],
    });

    t.row.add(['1.3', '2.3']) // <-- Fails
});
</script>
</head>

<body>
 <div id="demo" style="width:500px"> </div>
</body>
</html>
2
  • I cant see t.row declared/initialized in your code Commented Jul 12, 2015 at 9:16
  • did you debug and see the value for t.row? It is undefined. Commented Jul 12, 2015 at 9:16

1 Answer 1

4

You are very close. Here is the change I have done to your code:

a. While initializing DataTable, used capital D. b. Used .draw(); while adding row.

var dataSet = [
    ['1.1','2.1'],
    ['1.2','2.2']
];

$(document).ready(function() {
    $('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
 
    var t = $('#example').DataTable({
        data: dataSet,
        columns: [
            { "title": "Col 1" },
            { "title": "Col 2" }
        ]
    });             

    t.row.add(['1.3', '2.3']).draw(); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>

<div id="demo" style="width:500px"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.