Adding new datatable row with data attribute

Adding new datatable row with data attribute

tonelm2tonelm2 Posts: 5Questions: 2Answers: 0

I've been struggling this afternoon about adding a row to a table using datatable. The issue is I want the row to have a data attribute with a value from the data. The idea is to do this from a JSON response from an ajax command, so simplifying it to

https://jsfiddle.net/7uwb16q2/

$('#btnAdd').on('click', function() {
  $('#table').DataTable().row.add({
    "pid": "27",
    "Text": "3",
    "ED": "4",
    "Order": "6"
  }).draw();
});

It should add a new row, but I just get the message

DataTables warning: table id=table - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

Which I really dont understand. Can anyone shine any light on what I need to do please?

Answers

  • colincolin Posts: 15,117Questions: 1Answers: 2,583

    That's because you haven't defined any columns with columns.data, so DataTables assumes you're using array based data, so you'll need to add it as an array - see here: https://jsfiddle.net/xLmktjb5/

    Colin

  • tonelm2tonelm2 Posts: 5Questions: 2Answers: 0

    From my understanding if I want access to the pid from the data object, then I will need to define my colums. So, I tried to do it as:-
    https://jsfiddle.net/oj8h5s4v/

    But still get the same error.

    Am I not understanding something correctly? I need the row to have a data attribute so I can add action buttons to the row (at a later time) and get the id from the row data.

    Any ideas?

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    The Data Sources doc states this about using DOM sourced data:

    Note that when using a DOM sourced table, DataTables will use arrays as the data source

    It does say that you can use columns.data but you will need to define the array index instead of names.

    I removed the DOM rows and now your row.add() works as expected:
    https://jsfiddle.net/b0w83zh7/

    Kevin

Sign In or Register to comment.