简体   繁体   中英

unable to delete newly added rows on the table with dataTable jquery

I have a html table that has a content came from a database by using ajax and php.

When i try to add a new row manually by filling all the inputs and click save button it will add the data to the table.

My problem is when i try to delete the newly added rows and click the delete button on that specific row it doesn't delete. But when i try to delete the rows that came from the database it is deleted from the html table.

script:

$.ajax({
url: 'process.php',
type: 'post',
data: {tag: 'getData'},
dataType: 'json',
success: function(data){
        if(data.success){
            $("#myTable2 tbody").empty(); 
            $.each(data, function(index, record){
                if($.isNumeric(index)){
                    var row = $("<tr />");
                    $("<td />").text(record.name).appendTo(row);
                    $("<td />").text(record.age).appendTo(row);
                    $("<td />").text(record.gender).appendTo(row);
                    $("<td />").html(record.action).appendTo(row);
                    row.appendTo("#myTable2 tbody");
                }
            })
            }   

            var oTable = $('#myTable2').DataTable();

            $("#myTable2 tbody .dltRow").bind( 'click', function(event) {
                var row = $(this).closest('tr').get(0);
                oTable.row(row).remove().draw();

                oTable.row($(this).closest('tr')).remove().draw();
                $(this).parent().parent().closest('tr').remove();
                oTable.fnDeleteRow(oTable.fnGetPosition(row));

            });                 

            $('#Save2').on( 'click', function () {
                var data = [
                    $('#name').val(),
                    $('#age').val(),
                    $("[name='gender']:checked").val(),
                    "<center><button type='button' class='btn btn-default dltRow'><i class='glyphicon glyphicon-trash'></i></button></center>"
                    ];

                oTable.row.add(data).draw();
            });

        }

});

use event delegation to attach events to dynamically added delete buttons.

 $("#myTable2 tbody").on( 'click','.dltRow', function(event) {
            var row = $(this).closest('tr').get(0);
            oTable.row(row).remove().draw();

            oTable.row($(this).closest('tr')).remove().draw();
            $(this).parent().parent().closest('tr').remove();
            oTable.fnDeleteRow(oTable.fnGetPosition(row));

        });   

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