Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a Row from JQuery Datatables

Hi I am deleting the row from the table using fnDeleteRow function but the problem is that it deletes the correct row for the first time only and than start deleting the next row instead of that for which I am pressing the delete button.

here is my code

$(document).ready(function() {
        $(document).delegate('.but', 'click', function() { 

            var id = this.id; //getting the ID of the pressed button
            var name = this.name; //getting the name of the pressed button

            /****AJAX Function*********/
            $.post('/products/delete', {id:id}, function(data) {
                if(data == 1){ //In case if data is deleted

                    var oTable = $('#table_id').dataTable(); // JQuery dataTable function to delete the row from the table
                    oTable.fnDeleteRow( parseInt(name, 10) );// JQuery dataTable function to delete the row from the table
                  //  oTable.fnDraw(true);



               }
                else
                    alert(data);
            });
        });
    });

this.name gives the row number of the row associated with the pressed button as I don't know any method to calculate the rowIndex dynamically from the dataTable.

As I calculate the row number on the server side and associate that number with the button, so when I delete the row datatable rearranges its rowIndex on client side and server does not know any thing regard this.

Any help to resolve this issue.

like image 788
Najam-us-Saqib Avatar asked Dec 12 '22 11:12

Najam-us-Saqib


2 Answers

Try this:

$(document).ready(function() {
        $(document).delegate('.but', 'click', function() { 

            var id = this.id; //getting the ID of the pressed button
            var row = $(this).closest("tr").get(0);

            /****AJAX Function*********/
            $.post('/products/delete', {id:id}, function(data) {
                if(data == 1){ //In case if data is deleted

                    var oTable = $('#table_id').dataTable(); // JQuery dataTable function to delete the row from the table
                    oTable.fnDeleteRow(oTable.fnGetPosition(row));// JQuery dataTable function to delete the row from the table
                  //  oTable.fnDraw(true);
               }
                else
                    alert(data);
            });
        });
    });
like image 123
Kiran Avatar answered Dec 14 '22 00:12

Kiran


// Delete Row from dataTable - START //
    $('body').on('click', 'i.DeleteRow', function() {
          DeletedRow = $(this).parents('tr');
    });

    $('body').on('click', '.btnYES', function(){
        console.log('DeletedRow:', DeletedRow);
        $('#unitsTableDisplay').DataTable().row(DeletedRow).remove().draw();
    })
    // Delete Row from dataTable - END //
like image 30
dxpkumar Avatar answered Dec 14 '22 01:12

dxpkumar