How to delete current row with jquery datatable pl

2019-01-26 19:19发布

I use datatable plugin in a website. Normally I have only 1 datatable per page but in a special display I have 2 datable.

Actually I have this code

var oTable = $('.datatable').dataTable({
    'sPaginationType':'full_numbers',
    "iDisplayLength": 50,
    "oLanguage": {
        "sUrl": "js/locales/dataTables.french.txt"
    }
});

/* Add a click handler to the rows - this could be used as a callback */
$(".delete-ajax").click(function(event) {
    event.preventDefault();
    var answer = confirm("Supprimer l'élément ?")
    if (answer){
    var loading = $('.loading-notification');
    loading.removeClass('hidden');
        $(oTable.fnSettings().aoData).each(function (){
            $(this.nTr).removeClass('row_selected');
        });
        $(event.target).parents('tr').addClass('row_selected');
        var url = $(this).attr('href');
        var id = $(this).attr('data-ajax');
        var anSelected = fnGetSelected( oTable );
        $.ajax({
            type: "POST",
            url: url,
        data: "delete=true&id="+ id,
        async : true,
        success: function(msg) {
            loading.addClass('hidden');
            oTable.fnDeleteRow( anSelected[0] );
            }
        });
    }
});
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal ){
    var aReturn = new Array();
var aTrs = oTableLocal.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ ){
    if ( $(aTrs[i]).hasClass('row_selected') ){
        aReturn.push( aTrs[i] );
    }
}
return aReturn;
}

This code work well when I have only 1 datatable but when I have more I obtain In my console :

k is undefined
[Stopper sur une erreur]   h=a._iDisplayEnd;if(a.oFeatures.bServe...push(a.aoOpenRows[k].nTr)}}else{d[0]= 

Any idea on how to solve this problem ?

2条回答
对你真心纯属浪费
2楼-- · 2019-01-26 19:56

I am just sharing how I did it.

$(".delete-ajax").click(function(){
 var row = $(this).closest("tr").get(0);
 //ajax code goes here to delete row in the database
    $.ajax({
        type: "POST",
        url: url,
    data: "delete=true&id="+ id,
    async : true,
    success: function(msg) {
          loading.addClass('hidden');
          oTable.fnDeleteRow(oTable.fnGetPosition(row));
        }
    });
}

UPDATE: dataTable v1.10 I now use:

var row = $(this).closest("tr");
oTable.row(row).remove().draw();

For more details see: https://datatables.net/reference/api/row().remove()

查看更多
\"骚年 ilove
3楼-- · 2019-01-26 20:07

Here is how you can delete a row in the table (regardless the number of amount of tables in page)

I got two table in same page

I am not sure about how good is the id that you gave to the table, but if its ".datatable" then:

Add this function to your page

$(".datatable tbody").delegate("tr", "click", function () {
    var iPos = oTable.fnGetPosition(this);
    if (iPos !== null) {
        oTable.fnDeleteRow(iPos);//delete row
    }
});
查看更多
登录 后发表回答