JSFiddle - React, Tailwind, and code Playground
by Mike McAngus
HTML
<script src="http://cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<a class="addRow" href="#">add row</a>
<table id="example">
<thead>
<tr>
<th>Invoice ID</th>
<th>Vendor ID</th>
<th>Product ID</th>
<th>Seq Num</th>
</tr>
</thead>
<tbody>
<tr>
<td>Invoice 1</td>
<td>Vendor 1</td>
<td>Product 1.1</td>
<td>1</td>
</tr>
<tr>
<td>Invoice 1</td>
<td>Vendor 1</td>
<td>Product 1.2</td>
<td>2</td>
</tr>
<tr>
<td>Invoice 1</td>
<td>Vendor 2</td>
<td>Product 2.3</td>
<td>3</td>
</tr>
<tr>
<td>Invoice 1</td>
<td>Vendor 2</td>
<td>Product 2.5</td>
<td>5</td>
</tr>
<tr>
<td>Invoice 1</td>
<td>Vendor 2</td>
<td>Product 2.6</td>
<td>6</td>
</tr>
</tbody>
</table>
CSS
table, th, tr, td {
border: 1px solid black;
border-collapse: collapse;
}
td {
text-align: center;
}
.seqNum {
/* display: none;*/
}
JavaScript
var exampleTable;
function maxIntValue(table, colSelector) {
var valArray = exampleTable.column(colSelector)
.data()
.sort()
.reverse();
for (var i=0;i<valArray.length;i++) {
if (!isNaN(valArray[i])) {
return parseInt(valArray[i]);
}
}
return 0;
}
function addRow() {
var nextSeqNum = (maxIntValue(exampleTable, ".seqNum") + 1);
var col0 = 'Invoice 1';
var col1 = 'Vendor 3';
var col2 = 'Product 3.' + nextSeqNum;
var col3 = nextSeqNum;
exampleTable.row.add([col0, col1, col2, col3]).draw();
}
$(document).ready(function () {
// Initialize my table
exampleTable = $("#example").DataTable({
"columnDefs": [{
"targets": [-1],
"class": "seqNum"
}],
"fnCreatedRow": function (row, data, dataIndex) {
var seqNum = data[-1];
$(row).prop("id", "row_" + seqNum);
}
});
// Adds an empty row when the "add row" link is clicked
$('.addRow').on('click', function (event) {
event.preventDefault();
addRow();
});
});