Daniel A Sathish Kumar
Daniel A Sathish Kumar

Reputation: 157

J Query pagination plugin not working for dynamically added rows in html table

I'm spending for more than 6 hours for this issue. it would be better, if any one help me to solve this issue.

I'm trying to use jquery pagination plugin in dynamically added html table. But its not working. it gives exception. however its working fine for static html table.

Here is my code

 <link href="../assets/css/jquery.dataTables.min.css" rel="stylesheet" />
 <script src="../assets/js/jquery.dataTables.min.js.js"></script>

               <table id="productTable" >
                <thead class="alert-info text">
                    <tr>
                        <th><strong>Edit</strong></th>
                        <th><strong>Product Name</strong></th>
                        <th><strong>Introduction Date</strong></th>
                        <th><strong>URL</strong></th>
                        <th><strong>Delete</strong></th>
                    </tr>
                </thead>

Jquery is

function bindDate(res) {
    var d = res;
    $("#productTable tbody").remove();
    if ($("#productTable tbody").length == 0) {
        $("#productTable").append("<tbody></tbody>");
    }
    if (d != null) {
        for (var i = 0; i < d.length; i++) {
            $("#productTable tbody").append(
            "<tr>" +
            "<td onclick='edit(this);' data-toggle='modal' data-target='#myModal'>" + "<img src='../assets/imgs/edit.ico' Height='30' Width='30'/>" + "</td>" +
            "<td style='display:none;'>" + d[i].ID + "</td>" +
            "<td>" + d[i].ProductName + "</td>" +
            "<td>" + d[i].IntroDate + "</td>" +
            "<td>" + d[i].URL + "</td>" +
            "<td onclick='pdelete(this);'>" + "<img        src='../assets/imgs/delete.png' Height='30' Width='30'/>" + "</td>" +
            "</tr>"
            );
        }
    }
  $('#productTable').DataTable();
}

Upvotes: 0

Views: 363

Answers (1)

Fenn-CS
Fenn-CS

Reputation: 907

that is happening because jQuery events are not bound to dynamically added elements by default.. You need to use a concept called Event Delegation where you will have to have to make sure the table is dynamically added to a static element so u can use it as a reference.

$('body').on('event', '#productTable', function(event){
//Replace event with the right event, like click or something...

});

Find out more here Event Delegation and .on() Method. Also do some googling hope this helps

Upvotes: 1

Related Questions