I'm trying to code a button click in jQuery that will search all the row data returned from DataTables, find only rows that have an email address, then add the .selected class to that particular row.
I have been able to get the following code to work just fine, but it only adds the .selected class to the current view of the table. Not the entire data set. So, when the user switches pages or narrows the search the data that should have the .selected class does not have it.
$( '#testButton' ).click(function(){
$( '#table tr' ).each( function (){
var rowData = oTable.row( this ).data();
if( rowData !== undefined ){
if( rowData.email.length > 4 ){
//console.log( "found an email :"+rowData.email );
$( this ).addClass( 'selected' );
}
}
});
}
Here is the jQuery code I have tried to use, but I can't get it to work correctly. It does seem to add the .selected class however, it's not adding it to the correct rows. It seems to be randomly adding the .selected class to rows. The weird thing though is the console output line is identifying the correct row indexes and email addresses based on the json data set. Does anyone know how to correctly do what I'm attempting to do?
var oTable = $( '#table' ).DataTable({
'ajax': {
url: 'get-json-data.php',
type: "POST",
dataSrc: function ( data ) {
return data;
},
},
'columns': [
{
"data": "name",
"render": function ( data, type, row ) {
return "<a id='"+row.id+"'>"+data+"</a>";
}
},
{
"data": "company",
"render": function ( data, type, row ) {
return data;
}
}
],
stateSave: true,
responsive: true,
createdRow: function ( row, data, index ) {
row.setAttribute( 'id',data.id );
}
});
$( '#testButton' ).click(function(){
var rowData = oTable.rows().data();
$( rowData ).each( function ( i, e ){
if( rowData[i].email !== undefined ){
//only show data long enough to be an actual email address
if( rowData[i].email.length > 5 ){
// this shows the correct information
console.log( "On row "+i+" found this :"+rowData[i].email+" address" );
// this applies the selected class to the wrong row
$(oTable.row(i).node()).addClass('selected');
}
}
});
});
sample json data set returned from get-json-data.php:
{"id","1","name":"someName","email":"","company":"companyName"},
{"id","2","name":"someName1","email":"[email protected]","company":"companyName1"},
{"id","3","name":"someName2","email":"[email protected]","company":"companyName2"}
BTW: I'm using the jQuery DataTables plugin available Here version 1.10.15