How to Add new row to datatable using jquery datatable

By FoxLearn 2/16/2024 9:29:50 AM   352
This post shows you how to add new row to datatable using jquery datatable.net

For example

<table border="1">
    <thead>
        <tr><td>Customer ID</td><td>Customer Name</td>
        <tr>
    </thead>
    <tr>
        <td>01</td>
        <td>John</td>
    </tr>
    <tr>
        <td>02</td>
        <td>Lucy</td>
    </tr>
</table>

You can use fnAddData to add row with an array of the values that you want to add.

var table = $('#tbl').DataTable();
var total = table.data().count();
var column1 = 'col 1';
var column2 = 'col 2';
$('#tbl').dataTable().fnAddData([column1, column2 ]);

If you want to embed html control you can write.

var column1 = '<input type="text" id="AddressList_' + total + '__Name" name="AddressList[' + total + '].Name" value="' + data.Name + '">';

And from version 1.10 you can use row.add() method

var newRow = "<tr><td>col 1</td><td>col 2</td></tr>";
var table = $('#tbl').DataTable();
table.row.add($(newRow )).draw();