I'm using DataTable.js version 1.10.7 in my application. My intention is to get an Array of row data that was added to the table after initiation. I have followed a modified version of steps as in this documentation - https://datatables.net/reference/api/rows().data()
<!-- this form is filled and form values are added the datatable on submission-->
<div class="col-md-4">
<form action="../api/MaterialInPurchaseOrders/Create" id="create-material-in-purchaseOrder" method="POST">
<div id="name-group" class="form-group">
<label for="name">Material Name</label>
<select name="MaterialId" class="form-control" id="MaterialList"></select>
<br />
<label for="email">Quantity</label>
<input type="number" class="form-control" name="Quantity" placeholder="eg :- 100">
<label for="email">Quantity</label>
<input type="number" class="form-control" name="Cost" placeholder="eg :- 100">
</div>
<button type="submit" class="btn btn-default">Add Material to P/O<span class="fa fa-arrow-right"></span></button>
</form>
</div>
<!-- this table stores the rows that is being added from the form-->
<div class="col-md-8">
<table id="materials-in-purchase-order" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Material Id</th>
<th>Material Name</th>
<th>Quantity</th>
<th>Unit Cost</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Material Id</th>
<th>Material Name</th>
<th>Quantity</th>
<th>Unit Cost</th>
</tr>
</tfoot>
</table>
</div>
<button class="btn btn-success" id="get-table-data">Get Table Row Data</button>
<script>
// the Datatable handler
var materialsInPurchaseOrder = $("#materials-in-purchase-order").DataTable({
"dataSrc": "data",
"columns": [
{ "data": "MaterialId" },
{ "data": "MaterialName" },
{ "data": "Quantity" },
{ "data": "Cost" }
]
});
$(document).ready(function () {
// loading list boxes from database to an input selection list box in the form
loadListBox("../api/Materials/GetMaterials", "#MaterialList", "MaterialId", "MaterialName");
// on submission of the form the form values gets updated to the Datatable as a row.
$("#create-material-in-purchaseOrder").on("submit", function (event) {
var data = {};
data = getFormValues("#create-material-in-purchaseOrder");
$("#MaterialList option:selected").each(function () {
data["MaterialName"] = $(this).html();
});;
materialsInPurchaseOrder.row.add(data).draw(false);
event.preventDefault();
});
$("#get-table-data").click(function (event) {
var materials = materialsInPurchaseOrder.rows().data();
console.log(materials);
// looping through each row of the array and doing something
for (var material in materials) {
// unable to do this because materials is not an array :(
}
event.preventDefault();
});
});
</script>
I get the below output for the console.log() instead of an Array
[Object, context: Array[1], selector: Object, ajax: Object]
Some research I did, jQuery DataTables - Access all rows data
How can I get an Array of DataTable row data.?