Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract a selected row's data on Datatables

I have initialised a simple Datatable:

//initialise table
var dataTable = $('#example').DataTable({
    searching: false,
    responsive: true

});
//hide unnecessary columns
dataTable.columns(1).visible(false);
dataTable.columns(2).visible(false);
dataTable.columns(3).visible(false);
dataTable.columns(4).visible(false);
dataTable.columns(5).visible(false);
dataTable.columns(6).visible(false);
dataTable.columns(7).visible(false);
dataTable.columns(8).visible(false);

It can contain any number of records but I would like to take the values from all of the columns (only 1 is displayed to the user) and insert them into input fields (which may or may not be visible). I have successfully been able to select the rows using:

$('#example tbody').on( 'click', 'tr', function () {

       if ( $(this).hasClass('selected') ) {
           $(this).removeClass('selected');
       }
       else {
           dataTable.$('tr.selected').removeClass('selected');
           $(this).addClass('selected');
       }

   });

I have been looking into the Datatables API, row(), cells() etc and whilst I can view the data() method I simply can't see how to extract data from EACH cell on the row into the input text fields on the same webpage. I have also looked at fnGetSelectedData but I didn't get far as it always returned undefined via the console.

To explain the use case, it's essentially an Address Lookup. Each column in the table represents part of the address, I want to take the cells from the selected row and insert it into the form as a users selected address.

Any help is appreciated

like image 314
n34_panda Avatar asked Dec 29 '25 13:12

n34_panda


2 Answers

SOLUTION

Use the code below to get data for the selected row:

var data = $('#example').DataTable().row('.selected').data();

Then you can populate your input fields as shown below:

$('#name').val(data[0]); 
$('#email').val(data[1]); 

See this jsFiddle for demonstration.

NOTES

You can simplify your initialization code:

var dataTable = $('#example').DataTable({
    searching: false,
    responsive: true
    columnDefs: [
       {
          targets: [1,2,3,4,5,6,7,8],
          visible: false
       }
    ]
});
like image 176
Gyrocode.com Avatar answered Dec 31 '25 02:12

Gyrocode.com


To get an object with the values use:

yourTableVariable.rows({ selected: true }).data();

Then you can do something like this to get specific value(example id):

yourTableVariable.rows({ selected: true }).data()[0].id;
like image 22
Noob Avatar answered Dec 31 '25 03:12

Noob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!