Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  121] [ 1]  / answers: 1 / hits: 19499  / 8 Years ago, fri, april 1, 2016, 12:00:00

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


More From » jquery

 Answers
18

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
}
]
});

[#62730] Wednesday, March 30, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;