Reputation: 48
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 Datatables.net 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.
$("#partsList").DataTable({
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();
tbl.row.add([
data.invtid,
data.linenbr,
data.Bf,
data.Bu,
data.cnvfact,
data.origin
]).draw();
Any reason why this isn't working? I have tried and tried and searched everywhere and can't find the problem.
Upvotes: 0
Views: 212
Reputation: 6165
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 structure doesn't match the initial structure in several ways. Specifically, you start with an object and try to add an array, 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. (I don't know whether the add()
method will fill in missing properties with blanks or not; perhaps you can try it out and see.)
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.
Upvotes: 1