Inserting rows in middle of table

Inserting rows in middle of table

msand01msand01 Posts: 54Questions: 24Answers: 1

I am attempting to insert a row in the middle of my datatable, utilizing the first column as the sort order - eventually i would like to hide this column. It appears to work initially; however subsequent inserts (or deletes) reveal (I suspect) that the underlying cache hasn't in fact been updated, since the rows no longer appear in the correct order. I am obviously missing something but have been unable to fix it myself.
I have an example here: http://live.datatables.net/jekugolu/1/edit

Answers

  • msand01msand01 Posts: 54Questions: 24Answers: 1

    Maybe this is not possible?

    It does appear to work, but if you try to delete a row after adding, the added rows go back to the bottom.

    Here is the pertinent code code from the above live site:

            testTable = $('#test-table').DataTable({
                "data": dataForDataTables,
                "destroy": true,
                "pageLength": 25,
                "columns": [
                    { "data": "SortIndex" },
                    { "data": "DataGroup", "orderable": false },
                    { "data": "Number1", "orderable": false },
                    { "data": "Number2", "orderable": false },
                    { "data": "Label1", "orderable": false },
                    { "data": "Label2", "orderable": false },
                    { "data": "Delete", "orderable": false, "render": delete_icon },
                    { "data": "Insert", "orderable": false, "render": add_icon }
                ]
            });
    
    
            $('#test-table tbody').on('click', 'i.glyphicon-plus-sign', function (event) {
                var insertedRowIndex = testTable.row($(this).parents('tr')).index();
                addRow();
                var lastRowIndex = testTable.page.info().recordsTotal - 1;
    
                //re-number sortIndex column to reflect added row 
                $.each(testTable.rows().data(), function (i, row) {
                    var firstCell = testTable.cell(i, 0);
    
                    if (i < insertedRowIndex) {
                        firstCell.data(i);
                    }
                    else if (i >= insertedRowIndex && i != lastRowIndex) {
                        firstCell.data(firstCell.data() + 1);
                    }
                    else if (i == lastRowIndex) {
                        firstCell.data(insertedRowIndex);
                    }
                })
     
                testTable.order([0, 'asc']).draw();         
            });
    
    function addRow() {
        testTable.row.add({
            "SortIndex": testTable.page.info().recordsTotal,
            "DataGroup": $("#select-data").val(),
            "Number1": "",
            "Number2": "",
            "Label1": "",
            "Label2": ""
        }).draw();
    }
    
This discussion has been closed.