Add a row after the selected row in jQuery dataTables

后端 未结 2 788
攒了一身酷
攒了一身酷 2021-01-21 13:36

DataTable is defined as

var oTable = $(\'#table1\').dataTable({
    \'aaData\': [
                 [\'John\', \'ABC\', \'$90000\'], [\'Doe\', \'XYZ\', \'$100000         


        
相关标签:
2条回答
  • 2021-01-21 14:01

    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/

    0 讨论(0)
  • 2021-01-21 14:05

    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

    0 讨论(0)
提交回复
热议问题