Add a row after the selected row in jQuery dataTab

2019-02-26 03:56发布

DataTable is defined as

var oTable = $('#table1').dataTable({
    'aaData': [
                 ['John', 'ABC', '$90000'], ['Doe', 'XYZ', '$100000'], ['Alan', 'PQR', '$110000']
              ],
    'aoColumns': [
                 {'sTitle': 'Name'}, {'sTitle': 'Company'}, {'sTitle': 'Salary'}
     ]
});

An empty row is added as

oTable.fnAddData([' ', ' ', ' ']);

However, this adds to the bottom of the table. Is there a way we can add exactly below / above the selected row.

2条回答
老娘就宠你
2楼-- · 2019-02-26 04:43

I don't believe it is possible without some custom sorting functions. Position is based entirely on the sort. The developer backs this up here: http://bit.ly/1gtYHyk and here http://bit.ly/PxHKgM

查看更多
贼婆χ
3楼-- · 2019-02-26 04:47

Think you are too hasty to accept that you cant do what you want :) Of course it is possible, but it is hard to figure out under which circumstances. The question is not very specific. The following code inserts a new row just after the last row you have clicked :

var dataTable;
var options = {
    bSort: false,
    bPaginate: false
};

function initDataTable() {
  dataTable = $('#example').dataTable(options);
}

function attachClickHandler() {
    $("#example tbody tr").click(function(event) {
        var index=$(this).index();
        $("#insert").text('insert a row below the row you just clicked ('+index+')').attr('index',index).show();
    });
}

$("#insert").click(function() {
    var index=$(this).attr('index');
    var newRow = '<tr>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>'+
        '<td>new</td>' +
        '</tr>';
    dataTable.fnDestroy();
    $("#example tbody tr").eq(index).after(newRow);    
    initDataTable();
    attachClickHandler();
});

initDataTable();
attachClickHandler();

The idea is to insert the new row to the underlying DOM table, and then reinitialize dataTable when it is done. It works also by sorting, but for demonstration purposes I turn sorting off. As @scottysmalls mentions, dataTables is really sorting everything, so a new inserted row will immediately be sorted, and that would look like it was not inserted correct.

See demo -> http://jsfiddle.net/2AqQ6/

查看更多
登录 后发表回答