Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datatable Sorted Row

Note: I will be hiding the data column and hence I have to use jQuery Datatable API.

For my jQuery Datatable, each row have a button beside it. The purpose of the button is to retrieve the column data. The column data will be hidden.

For my button click event, this is my code.

    $('#Table').on('click', '.Button', function () {
        var tr = $(this).closest("tr");
        var rowindex = tr.index();
        //Get row based on index
        var rowData = $("#Table").DataTable().row(rowindex).data();
        var data = rowData.Data;
    });

This code is working, however there is one problem.
It is not able to retrieve the data of the sorted column.

For example, before Sorting,
Row 1 - Index 0 Data - A
Row 2 - Index 1 Data - B

After sorting,
Row 2 - Index 0 Data - B
Row 1 - Index 1 Data - A

Clicked on Data B row button, Data Gotten: A

Hopefully I have explained my problem clear enough. Thanks!

Updated Fiddle: https://jsfiddle.net/mt4zrm4b/3/

like image 644
Jiawei Tan Avatar asked Jan 15 '16 07:01

Jiawei Tan


People also ask

How do you arrange data in ascending order in DataTable?

Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.

How do you sort data in an HTML table?

Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table.

How do I sort a data table in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.


1 Answers

You need to pass in your selector tr as the rowSelector parameter for row().

DOM elements can be given as a row selector to select a row in the DataTabels API from that DOM element. This can be useful for getting data from a row, or performing other row based operations, when you have only the DOM node for reference, for example in an event handler.

The reason is because if you were to sort, the row indexes that DataTables doesn't get updated. It's recommended to select the row via your tr, like this:

$('#Table').on('click', '.Button', function() {
    var tr = $(this).closest("tr");

    // Get row based on tr instead.
    var rowData = $("#Table").DataTable().row(tr).data();
    var data = rowData.Data;
    alert(data);
});

See this updated fiddle for an example.

like image 153
Jia Jian Goi Avatar answered Oct 05 '22 22:10

Jia Jian Goi