Datatable cannot get row index after search - javascript

I have create a datatable and can get the row index of the data before any search action.
dataArray=[
[1, "Name1"],
[2, "Name2"], ,
[3, "Name23"],
];
var table = $('#tblName').DataTable( {
scrollY: '40vh',
"scrollX": true,
scrollCollapse: true,
paging: false,
responsive:true,
data: dataArray,
} );
$('#tblName tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected1') ) {
}
else
{
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
$(this).removeClass('selected1');
}
} );
$(this).addClass('selected1');
}
} );
I want to get the row index to change the value of the dataArray . The following is the input text searchName to filter the datatable with keyword match with dataArray in column 1
$('#searchName').on( 'keyup', function () {
table
.columns( 1 )
.search( this.value )
.draw();
} );
$('#tblName tbody').on( 'click', 'tr', function () {
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
var rowindex=$(this).closest('tr').index();
var dataWareHouse = table.row( this ).columns(1).data();
var selectedName = dataArray[0][rowindex];
console.log(selectedName);
}
} );
} );
After filter the datatable with input text searchName, I cannot get the correct old row Index. For example input in searchName:
2
The datable will show only 2 row with Name of Name2 and Name23,
However, when i click the first row, it show the Name1. The correct return data should be Name2

Well, you can't rely on DOM index when you are using search. Since some data will not be displayed due to filtering. But DataTable provide API method to get correct indices, data, etc.
$('#tblName tbody').on( 'click', 'tr', function () {
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
var rowindex = table.row(this).index();
var rowData = table.row(this).data();
var selectedName = table.row(this)[0];
var anotherWayToGetName = table.cell(rowIndex, 0).data();
console.log(rowIndex, rowData, selectedName, anotherWayToGeName);
}
} );
} );

Related

How to set title in each table TD from TD text ( legacy datatable ) using jquery?

So the question would be, in a legacy jquery datatable ( not the "new" version of it ) how can i set a title on the cell(td) with its content?
And here is the code:
In the properties of the datatable($("#MySpecialDatatable").datatable({properties})):
...
"fnDrawCallback": function(oSettings) {
$("#MySpecialDatatable tbody tr").each(function () {
var nTds = $('td', this);
$(nTds).each(function () {
var td = this;
td.setAttribute('title', $(td).text());
});
});
},
...

How to combine two JavaScript code blocks

I am new on javascript and I am trying to combine 2 javascript blocks but I am falling apart?
FIRST BLOCK
<script>
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('table.table tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+' ARA" />' );
} );
// DataTable
var table = $('table.table').DataTable();
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
} );
</script>
SECOND BLOCK
$('table.table').DataTable({
"order": [
[0, "desc"]
],
paging: true,
"oLanguage": {
"sUrl": "js/dil/LANGUAGE.json",
}
} );
I want to add "oLanguage" and "order" lines to first javascript. What should I do?
Just copy-paste array from DataTables to first part:
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('table.table tfoot th').each(function () {
$(this).html('<input type="text" placeholder="'+$(this).text()+' ARA" />');
});
// DataTable
var table = $('table.table').DataTable({
order: [
[0, "desc"]
],
paging: true,
oLanguage: {
sUrl: "js/dil/LANGUAGE.json",
}
});
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
});
});
Note DataTables used to have it's variables in hUngarianNotation and later on moved to camlCase, so it's most likely your oLanguage is not recognized by new API

Tooltip does not work with pagination on datatables

How can I get my tooltip being displayed when using pagination within the datatable plugin?
I am using the plugin protip in connection with datatables to display tooltips, when text inside a column is too long. The tooltips plugin already works with the following snippet:
//Datatable Setup
jQuery(document).ready(function($) {
var table = $('#irp-table.raab').DataTable({
"columnDefs": [
{ visible: false, targets: 2 },
{ className: 'mdl-data-table__cell--non-numeric', targets: [0, 1]}
],
"order": [[ 0, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="3">'+group+'</td></tr>'
);
last = group;
}
} );
}
} );
//Initialize ToolTip
jQuery(document).ready(function($) {
$.protip();
});
//ToolTip hover behaviour
jQuery(document).ready(function($) {
$('td').bind('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow()
}
}).mouseenter();
});
However it just works on the first site for the case I am using pagination on my datatable and navigate to another site.
SOLUTION
You need to use drawCallback to initialize tooltips every time DataTables redraws the table. This is needed because TR and TD elements for pages other than first are not present in DOM at the time first page is displayed.
Also the call to mouseenter() is not needed.
For example:
"drawCallback": function ( settings ) {
var api = this.api();
// ... skipped ...
$.protip();
$('td', api.table().container()).on('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow();
}
});
}
LINKS
See jQuery DataTables: Custom control does not work on second page and after for more examples and details.

Individual column searching in Pentaho CDE BI server

Table component in CDE Pentaho is based on datables, I wanted to implement this functionality in my tables https://datatables.net/examples/api/multi_filter.html
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable();
// Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
} );
I can't get it to work, I got Error processing component message, I tried including it as js snippet, as an external source, in post fetch and in post execution function, I thought that the lack of indexes for every column was causing the problem, I included the indexes in output options, it didn't work either,
I also found this alternative http://jsfiddle.net/CmMfJ/2/#collaborate
var table = $('#example').DataTable();
$("#example tfoot th").each( function ( i ) {
var select = $('<select><option value="">All</option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var term = $(this).val()!=='' ? '^'+$(this).val()+'$' : '';
table.column( i )
.search(term, true, false )
.draw();
} );
table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
});
I didn't get any errors with that code but it doesn't work, the table doesn't change, in both cases In Post Execution function I did this: function f(){ code }, I also changed the variable #example for the name of my table, nothing worked, any help would be really appreciated, thanks.
your postExecution approach might be the right one but you can't create a new DataTable over that div. It has already been created.
If you inspect the this object during the postExecution execution, one of the fields (can't remember which) gives you access to your DataTable object (the var table on your example).

Clone a selected row in DataTables?

I am currently able to delete a selected row, and now I want to duplicate/clone the selected row. Sometimes adding rows to DataTables can be tricky because the pagination will not update, so clone and append.
http://jsfiddle.net/BWCBX/30/
jQuery
var oTable;
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody tr").click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler for the delete row */
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
if ( anSelected.length !== 0 ) {
oTable.fnDeleteRow( anSelected[0] );
}
} );
/* Init the table */
oTable = $('#example').dataTable( );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}
In order to respect paging of jquery datatables the clone method should be calling the fnAddData function,
$('#clone').click( function() {
var anSelected = fnGetSelected( oTable );
console.log(anSelected);
var data=[];
$(anSelected).find('td').each(function(){data.push($(this).text());});
oTable.fnAddData( data );
} );
http://jsfiddle.net/BWCBX/32/
You need to add the click listener for selecting to these new rows as well.
For example,
$('#clone').click( function() {
var anSelected = fnGetSelected( oTable );
var data=[];
$(anSelected).find('td').each(function(){data.push($(this).html());});
var row=oTable.fnAddData( data );//returns the index of the row added
$(oTable.fnGetNodes(row)).click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
} );
http://jsfiddle.net/BWCBX/33/
I implemented using the .clone() jQuery, see: jsfiddle
$('#clone').click(function(){
var anSelected = fnGetSelected( oTable );
anSelected.clone().insertAfter( $("table").find("tr").last());
$("table").find("tr").last().removeClass("row_selected");
});
Hope this help

Categories