blackandorangecat blackandorangecat - 3 months ago 54x
jQuery Question

DataTables, calculated column

I am trying to create a column in my table using the DataTable plugin, that is calculated using values from two previous columns.

Something like this.. (Price)(QTY)=Total

|| Price || QTY || Total||
|| 5 || 2 || 10 ||
|| 10 || 3 || 30 ||
|| 4 || 1 || 4 ||

I feel like it should be simple, but I can't get it to work. Here is a similar question I tried to follow.

Here is my JS file where I am initializing the table

var table = $('#tempPOs').DataTable( {
dom: 'frtip', //Bfrtip (removed the B to get rid of the buttons)
ajax: '/inventory/DTResources/php/table.tempPOs.php',
columns: [
{ "data": "pmkPart" },
{ "data": "PartNumber" },
{ "data": "Description" },
{ "data": "fnkManufacturer" },
{ "data": "Notes" },
{ "data": "EachPrice", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
{ "data": "Quantity" },
{ "data": "Username" },
data: null,
className: "center",
defaultContent: '<a href="" class="editor_remove">Remove</a>'
select: true,
lengthChange: false,
buttons: [
{ extend: 'create', editor: editor },
{ extend: 'edit', editor: editor },
{ extend: 'remove', editor: editor }

} );

Here is my HTML

<th>Part ID</th>
<th>Part Number</th>
<th>Part Price</th>
<th>Total Price</th>

Anyone able to point me in the right direction?


You can use the render option similar to how you used it for the "EachPrice" field. There is a built-in function documented here if you want to get more information, but I'll outline what it would look like for you below.

columns: [
    /*other columns omitted for example*/
        "data": null, //data is null since we want to access ALL data
                      //for the sake of our calculation below
        "render": function(data,type,row) { return (data["price"] * data["quantity"])}


In this way you can use other columns from data to render output for this column.

This option can be used to display basically anything you want, as long as it can be calculated with a function. If you want to get more information on the usage of the render option, take a look at the link above.