trouble706 trouble706 - 1 year ago 97
Javascript Question

Having trouble adding row to DataTable

I am building a jquery datatable with JavaScript object. Table builds fine. Then, on a user's imput, I need to add a row. This is where I am having a problem. I have researched this on and on SO. Everything I have read indicates that what I am doing should work, but it doesn't. No row is added. Here is my code when DataTable is initialized.

data: data,
"order": [[1, "asc"]],
"scrollY": "800px",
"scrollCollapse": true,
"paging": false,
columns: [
{sTitle: "InvtId", data: "invtid", "defaultContent": '', 'className': 'invtId'},
{sTitle: "Line Nbr", data: "linenbr", 'className': 'lineNbr', "defaultContent": 'TEST'},
{sTitle: "BF", data: "BFval", "defaultContent": ''},
{sTitle: "BU", data: "BUval", "defaultContent": ''},
{sTitle: "CnvFact", data: "cnvfact"},
{sTitle: "Origin", data: "origin"},
{sTitle: "Line Tot", data: "linetot"},
{sTitle: "Description", data: "descr"},
{sTitle: "Quantity Ordered", data: "ordqty"},
{sTitle: "Quantity Ship", data: "qtyship"},
{sTitle: "Unit", data: "unitdesc"},
{sTitle: "Sales Price", data: "slsprice"},
{sTitle: "Wood Cost", data: "wood"},
{sTitle: "Treatment Cost", data: "treat"},
{sTitle: "Adjustments", data: "trtadj"},
{sTitle: "Misc", data: "misc"},
{sTitle: "Freight", data: "freight"}

Then, after a user's input, I am collecting data. This is an example of data being passed to add the new row. This isn't the entire object. Just trying to make sure that this is clear to read. All fields are covered in passing.

Object {invtid: "APGC1DBTR061008", Bf: 880, Bu: 0.88, linenbr: 66536, cnvfact: 0, Adj: "-45"Bf: 880, Freight: "22"}

And this is my code to add the new row. I am passing the data into the method with the variable name data...

var tbl = $("#partsList").DataTable();

Any reason why this isn't working? I have tried and tried and searched everywhere and can't find the problem.

Answer Source

From the doc on row.add():

If a data structure is used (i.e. array or object) it must be in the same format as the other data in the table (i.e. if your table uses objects, pass in an object with the same properties here!).

You'll notice that your array structure doesn't match the initial structure, which is an object. Specifically, there isn't any Bf or Bu in the original table--you have them as BFval and BUval--and a number of properties are missing.

So first, change your original table create from this:

$("#partsList").DataTable({ //etc.

to this:

var tbl = $("#partsList").DataTable({ //etc.

Then get rid of this:

var tbl = $("#partsList").DataTable();

and just start with this:

tbl.row.add([ //etc.

And make sure that your data matches.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download