Silverwulf
Silverwulf

Reputation: 109

Datatables get row Data without clicking on it

I'm using DataTables to show a list of messages.

I need a way to get a specific row of data based off an id being passed to the page on the Query string.

ex. www.webpage.com?id=2

I already have the id in a jQuery variable. Now I just need to access the DataTable row associated with that id.

Basically, I need to reference the row, without having clicked on it.

Any suggestions?

Upvotes: 4

Views: 28503

Answers (4)

xeo
xeo

Reputation: 832

fnGetData is now obsolete. this documents the cell().data() access pattern in the current version https://datatables.net/reference/api/cell().data()

Upvotes: 0

Daniel
Daniel

Reputation: 37071

One way could be to use fnGetPosition and fnGetData

var rowIndex = table.fnGetPosition( $("some selector").closest('tr')[0] );
//some selector = should select some hidden element inside a row that 
//contains the relevant id
var aData = table.fnGetData( rowIndex  );
alert(aData[0]);// will show first column data

Here a working jsfiddle example of an external button that selects row with specific ID

Another example that select the row with specific ID on page load(ready)jsfiddle example N#2

Take a look at the function

$("#wow").click(function() {

    var rowIndex = table.fnGetPosition($("#example input[value=\'TridentVal\']").closest('tr')[0]);
    alert(rowIndex);
    var aData = table.fnGetData(rowIndex);
    alert(aData[0]); // will show first column data
});​

This is the way to select an input with relevant data... :

$("#example input[value=\'TridentVal\']")

example is table id , replace TridentVal with the needed ID

Upvotes: 8

dnagirl
dnagirl

Reputation: 20456

If you use the TableTools extension, then you can use fnSelect(). From the docs:

$(document).ready( function () {
    $('#example1').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sRowSelect": "single"
        }
    } );

    // Select the first row in the table automatically
    var oTT = TableTools.fnGetInstance( 'example1' );
    oTT.fnSelect( $('#example tbody tr')[0] );
});

You'd of course want to modify the selector so it chooses the row that has your id.

Upvotes: 1

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

First you have to get your table row using jQuery.

var $rowNode = $('#myTable').find('tbody tr:eq(0)').get(0);

Then you use fnGetData to get the row data.

var data = table.fnGetData($rowNode);

fnGetData acccepts a row node or an integer, so you can pass the row index as parameter too.

demo

Upvotes: 3

Related Questions