2

I am using jquery datatables and I am having trouble grabbing the row data on click event. How can I get my data object from my datatable on row click event?

What I do:

  1. jquery post to get a json response load json response as data into datatable (array of objects)
  2. jquery, register click event on
  3. datatable rows when user clicks on row, need to get data object for row clicked on

My current code:

function contactSearchListTable(data) {
  // data is array of javascript object
  console.log('contactSearchListTable()');
  $(contactSearchResultsTableElement + ' tbody').off();
  if ( $.fn.dataTable.isDataTable(contactSearchResultsTableElement) ) {
    $(contactSearchResultsTableElement).DataTable().destroy();
  }
  if (data.length == 0) {
    $(contactSearchResultsTableElement).html('');
  }
  var table = $(contactSearchResultsTableElement);
  var params = {"data":data
                ,"info": false
                ,"searching": false
                ,"ordering": false
                ,"lengthChange": false
                ,"columns":[
                  {"data":"id","visible":false}
                  ,{"data":"name","title":"Name","class":"clickable"}
                  ,{"data":"phoneHome","title":"Home","class":"clickable"}
                  ,{"data":"phoneWork","title":"Work","class":"clickable"}
                  ]
                };
  var dt = table.dataTable(params);
  $(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function () {
    console.log(this); // <tr> html from datatable
    // **** need to get hidden ID value here, HOW?
  } );
}

1 Answer 1

3

You can access the data using row().data() function, change you click handler to:

$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function (){
   var data = dt.api().row(this).data();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I'll try this. My previous attempts were missing the '.api()'. Did not realize that was needed.
updated api from datatables doesn't require the api() anymore. I used: dt.row(this).data();
@SpoiledTechie.com, if you use dataTable() to initialize the table as the original poster, it's required. Otherwise if you use DataTable() to initialize, it's not required.
@Gyrocode.com your object dt says the table is already initialized. :) So if its already initialized, you don't need the dataTable() method. No biggie. Just letting everyone else know what I did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.