简体   繁体   中英

How to append data to datatables in jquery?

I have been trying to append data to a data table in jquery, data is appending to data table but data table is not working properly that means sorting, pagination, the search is not working. Even data is there in the data table but it is showing 0 records. Am trying to make all functionalities work properly, please help me on this.

<table id="newexample1">
    <thead>
        <tr>
            <th>Name</th>
            <th>Employee</th>
            <th>InTime</th>
        </tr>
    </thead>
    <tbody class="tablebody">
    </tbody>
</table>
<script>
    function newfunction() {
        $(".tablebody").append("<tr onclick='historyfunction()'><td>Sasi Kumar</td><td>Suresh Kumar</td><td>21/06/2019 10:59:02</td></tr>");
    }
</script>
<script>
    $(document).ready(function() {
        $('#newexample1').DataTable();
    });
</script>

Am expecting a proper data table.

function newfunction() {
        $(".tablebody").append("<tr onclick='historyfunction()'><td>Sasi Kumar</td><td>Suresh Kumar</td><td>21/06/2019 10:59:02</td></tr>");
        $(".tablebody").append("<tr onclick='historyfunction()'><td>omar omar</td><td>Suresh Kumar</td><td>21/06/2019 10:59:02</td></tr>");
    }

    $(document).ready(function() {
        newfunction();
        $('#newexample1').DataTable();
    });

Here a working JSfiddle

In your code newfunction() is never called so the table is empty when Datatable tries to render the table. Add row before render Datatable is instantiated in $(document).ready(function() (otherwise you get 0 rows table). Otherwise, if you would add rows after Datatable is rendered, use rows.add() and then redraw the table on the screen with draw() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM