Error when adding object to row

Error when adding object to row

rudeboirudeboi Posts: 3Questions: 1Answers: 0
edited July 2014 in Free community support

Here's the error:

DataTables warning: table id=example - Requested unknown parameter '0' for row 0. For more information about this is the error:

Here's my code:

    <script type="text/javascript" class="init">
    $(document).ready(function() {
        var t = $('#example').DataTable();

        $('#addRow').on( 'click', function () {
            //add obj instead of array
            console.log("adding data...");
            t.row.add( 
                {
                    "Column 1" : 0,
                    "Column 2": 1,
                    "Column 3": 2,
                    "Column 4": 3,
                    "Column 5": 4
                }).draw();

        } );

        // Automatically add a first row of data
        $('#addRow').click();
    } );

    </script>

</head>

<body>          
    </div><button id="addRow">Add new row</button>

    <table id="example" >
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
                <th>Column 4</th>
                <th>Column 5</th>
            </tr>
        </thead>

        <tfoot>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
                <th>Column 3</th>
                <th>Column 4</th>
                <th>Column 5</th>
            </tr>
        </tfoot>
    </table>

Please help mon!!!

This question has an accepted answers - jump to answer

Answers

  • rhinorhino Posts: 80Questions: 2Answers: 17
    edited July 2014

    Try changing to this?

    t.row.add( [0, 1, 2, 3, 4] ).draw();
    

    Also you have a </div> without an opening <div>... not that that is related to you problem. :)

  • rudeboirudeboi Posts: 3Questions: 1Answers: 0

    Adding an array like what that works fine. I would prefer adding objects though. I'm just wondering if I'm doing something wrong or it's a bug because I feel like I'm following the API. Good catch with the div tag too @rhino

  • rhinorhino Posts: 80Questions: 2Answers: 17
    Answer ✓

    When you initialize your datatable, add the columns.data option to tell the API how to associate object keys to columns:

    var t = $('#example').DataTable({
      columns: [
        {data: "Column 1"},
        {data: "Column 2"},
        {data: "Column 3"},
        {data: "Column 4"},
        {data: "Column 5"}
      ]
    });
    
  • rudeboirudeboi Posts: 3Questions: 1Answers: 0

    Thanks bredrin!!!

This discussion has been closed.