is it possible to add a row to the beginning of the table?

is it possible to add a row to the beginning of the table?

drfunkdrfunk Posts: 58Questions: 8Answers: 0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,735

    the order of the rows is dependent on the order of the table. This blog presents a solution to place rows at the top or bottom of the table.

    Kevin

  • drfunkdrfunk Posts: 58Questions: 8Answers: 0

    here is my code snippet:
    $(document).ready(function() {
    var t = $('#ncs').DataTable();

    $('#addRow').on( 'click', function () {
        t.row.add( [
            'John',
            'Doe'
        ] ).draw( true );
    
    } );
    

    } );

    where would I put position=top

  • kthorngrenkthorngren Posts: 20,141Questions: 26Answers: 4,735
    Answer ✓

    Put it before the Datatables init code, just like the examples. In your case it looks like before var t = $('#ncs').DataTable(); would be the correct place.

    Kevin

  • vordanvordan Posts: 1Questions: 0Answers: 0
    edited January 7

    I know this is maybe a bit late, but let me show my solution.

    The use case is: when the user adds new record, we want to insert it at the top of the table, so the user knows that it was saved.

    This is a bit of a hack, but works for the purpose, and doesn't need any plugins.
    First, at the beginning of the table, add a new column, I usually name it row_order.
    Give it a defaultContent of 0 (zero). Usually, I hide it, but leave it visible for the moment, just to test things.
    Add this column to the order property of the table, before any other columns:
    order: [[0,"asc"], [4,"asc"]] - in this case, we order by row_order first, then by column with index 4.

    Next, in your select from the database add '1' as row_order to the select query, usually at the end of everything else.
    Or, if you have the data in some array, put "row_order": "1" in each row.

    When you show the data, all rows will have '1' as value of the row_order, and nothing is out of the ordinary - the table is sorted as previously, the click on ordered column headings works as usual.

    Then, do the add in your code:

    $('#datatable').DataTable().row.add(row_record).draw();
    
    

    The Datatable will add the row and automatically reorder the table, thus putting the new row at the top, since the default value of row_order is 0.
    On the next read from the database, all rows will have value '1' for the row_order, and the item will be sorted where it should be.

    Hope this helps somebody.

Sign In or Register to comment.