how to get the inner html value from Datatable cell - javascript

I am newbie to DataTable. here I am trying to get the of first cell value of a row when I click the viewlink associated with the row, instead of the value I am getting [object object].
heres my code
$(document).ready(function() {
// Delete a record
$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData($(this).parents('tr')[0]);
alert(aData);
} );
// DataTables init
var oTable=$('#example').dataTable( {
"sDom": "Tfrtip",
"sAjaxSource": "php/browsers.php",
"aoColumns": [
{ "mData": "browser" },
{ "mData": "engine" },
{ "mData": "platform" },
{ "mData": "grade", "sClass": "center" },
{
"mData": null,
"sClass": "center",
"sDefaultContent": 'view / Delete'
}
]
} );
} );
HTML Table:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th width="30%">Browser</th>
<th width="20%">Rendering engine</th>
<th width="20%">Platform(s)</th>
<th width="14%">CSS grade</th>
<th width="16%">Admin</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Browser</th>
<th>Rendering engine</th>
<th>Platform(s)</th>
<th>CSS grade</th>
<th>Admin</th>
</tr>
</tfoot>
Now when I Click on the view I need to Navigate to another page with the id like
view.php?id=125
Thank you

$('#example').on('click', 'a.editor_view', function (e) {
e.preventDefault();
var rowIndex = oTable.fnGetPosition( $(this).closest('tr')[0] );
aData = oTable.fnGetData(rowIndex,0);
alert(aData);
} );
From the api docs:
fnGetData
Input parameters:
{int|node}: A TR row node, TD/TH cell node or an integer. If given as a TR node then the data source for the whole row will be returned. If given as a TD/TH cell node then iCol will be automatically calculated and the data for the cell returned. If given as an integer, then this is treated as the aoData internal data index for the row (see fnGetPosition) and the data for that row used.
{int}: Optional column index that you want the data of.

Assuming your first row is your id, would you want to include the links in your dataTable initializer like this?
$(document).ready(function () {
var oTable = $('#example').dataTable({
"aoColumnDefs": [{
"fnRender": function (oObj) {
var id = oObj.aData[0];
var links = [
'View',
'Delete'];
return links.join(' / ');
},
"sClass": "center",
"aTargets": [4]
}, {
"sClass": "center",
"aTargets": [3]
}]
});
});
see: http://jsfiddle.net/9De6w/

Related

Jquery datatables - How count numbers of rows?

I am using to Jquery datables to create a table with row details . Everything working fine Only the number of entries
The current logic is counting the parents row + child rows. I want to count only parents rows which are 4. My result should be Showing 1 to 10 of 4 entries.
In my Json file, I have recordsTotal: 16 which is the total rows parents + child. When I change to 4 which is number of parents rows the table will show me only first record (Ticket id 1 + its 3 child rows ) as it's counted as 4 entries.
Any suggestions please how can I update ? Thank you.
$(document).ready(function() {
function format ( d ) {
d.Items.sort(function compare(a,b) {
if (a.Line_No < b.Line_No)
return -1;
if (a.Line_No > b.Line_No)
return 1;
return 0;
});
var x = '<table class="nowrap table table-bordered table-hover" cellspacing="0" width="100%"><thead><tr><th>Line No</th><th>Line Level Issue</th><th>Created Date</th><th>Created By</th></tr></thead><tbody>' ;
$.each(d.Items, function( index, value ) {
x += '<tr><td>' + d.Items[index].Line_No + '</td><td>' + d.Items[index].Line_Level_Issue + '</td><td>' + d.Items[index].Created_Date + '</td><td>' + d.Items[index].Created_By + '</td></tr>';
});
x +='</tbody></table>';
return x;
}
var dt = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"deferRender": true,
"lengthChange": true,
"pageLength": 10,
"language": { "emptyTable": "No matching records found",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"zeroRecords": "No matching records found" },
"ajax": "https://api.myjson.com/bins/vwjfc",
"columns": [
{
"class": "details-control",
"data": "Ticket_id"
,render : function(data, type, row) {
return ' ' + data;
}
},
{ "data": "Order_Level_Issue" },
{ "data": "Geo" },
{ "data": "Region" },
{ "data": "Territory" },
{ "data": "Market" },
{ "data": "Country" },
{ "data": "SoldTo_Number" },
{ "data": "SoldTo_Name" },
{ "data": "Order_Numer" }
],
"order": [[0, 'asc'],[1, 'asc']]
} );
var detailRows = [];
$('#example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center left;
cursor: pointer;
}
tr.details td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center left;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<table id="example" class="nowrap table table-hover table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>TicketT id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticket id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
I assume the problem was not dataTables at all but your ajax call, since you are using serverSide your server side is the one who sends the data the table will display including the total of records so in your ajax response you have:
{draw: 1, recordsTotal: 16, recordsFiltered: 16, data: Array(4)}
So all you have to do is work in your server side script in order the reflect the expected output.
Hope it helps

Get value of all checkbox selected in jQuery Datatables

I have the next Datatable
HTML
<table id="example" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Iden.</th>
<th>Nombres</th>
<th>Sel.</th>
</tr>
</tfoot>
</table>
JS
$('#example').DataTable({
scrollX: true,
deferRender: true,
"aaData": data.Data,
"columns": [{ data: "ID" },
{ data: "Identificacion" },
{ data: "Nombres" },
{ "data" : null,
"targets" : -1,
"orderable" : false,
"className" : "all",
"width" : "20px",
"render" : function(data, type, full) {
let texto = "";
texto = '<input type="checkbox" id="check_test" value="' + data.ID + '" />';
return texto;
}
}
]
});
I want get value of the selected checkboxes, so i tried this
var aux = [];
aux = $('#example tbody input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
however, this only obtains the values selected from the active page of the pagination datatable
How can I get the value of the selected checkboxes on all pages of datable?
Use $() DataTables API method to retrieve data from all pages, not just first page.
For example:
var $checkboxes = $('#example').DataTable().$('input[type=checkbox]:checked');

aoColumns of datatables are not working

Please find attached the application picture, where the column ORDER ID is not showing, and instead of that, is showing the PLUS sign. So all the columns should shift for one to the right.
ajax
And all the time when I run the application it shows me this error message:
DataTables warning (table id = 'companies'): Added data (size 3) does not match known number of columns (4)
var oTable;
$('#companies tbody td img').live('click', function () {
var nTr = this.parentNode.parentNode;
if (this.src.match('details_close')) {
/* This row is already open - close it */
this.src = "/Content/images/details_open.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
this.src = "/Content/images/details_close.png";
var orderid = $(this).attr("rel");
$.get("Me?OrderID=" + orderid, function (detalet) {
oTable.fnOpen(nTr, detalet, 'details');
});
}
});
/* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'AjaxHandler',
"bJQueryUI": true,
"aoColumns":
[
{ "bSortable": false,
"bSearchable": false,
"fnRender": function (oObj)
{
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '" />';
}
},
null,
null,
null
]
});
<table id="companies" class="display">
<thead>
<tr>
<th> </th>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
You should specify the column number in the aoColumns definition, e.g.:
"aoColumnDefs":[
{
"mData": null,
"bSortable": false,
"bSearchable": false,
"fnRender": function (oObj) {
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '" />';
}
},
{ "mData": 0 },
{ "mData": 1 },
{ "mData": 2 },
{ "mData": 3 }
]
And the HTML markup:
<table id="companies" class="display">
<thead>
<tr>
<th></th>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>
Use the following structure for aoColumns:
"aoColumns": [
{
"mData": 0,
"bSortable": false,
"bSearchable": false,
"mRender": function (data, type, full){
return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + data + '" />';
}
},
{ "mData": 1 },
{ "mData": 2 },
{ "mData": 3 }
]
Use the following HTML markup:
<table id="companies" class="display">
<thead>
<tr>
<th>Order ID</th>
<th>Customer ID</th>
<th>Ship Address</th>
<th>Country</th>
</tr>
</thead>
<tbody></tbody>
</table>

How to disable sorting on specific column while searching is functional

I am using DataTable (http://www.datatables.net) in order to get desired functionality including sorting columns and searching within columns from Table Heading individually. Initializing is as follow which returns api and searching functionality is achieved.
$('#table2').DataTable()
Now Problem is when I have to disable sorting on checkbox and I have to use following line of code.
$('#table2').dataTable( {
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
] } );
it does apply sorting disabled on column but search functionality within column also doesn't work. Is there any way I can pass any parameter in DataTable({something}) in order to disable sorting on first column or please help me to combine (api & jquery object) method in order to achieve desired functionality.
$('#table2').DataTable();
$('#table2').dataTable();
<table class="table table-striped draggable sortable dataTable" id="table2">
<thead>
<tr>
<th class="text-center"> <input class="check_box_all no-sort" id="check_all" type="checkbox" title="Check All"></th>
<th class="text-center">Company Name </th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td class="text-center"><input type="checkbox" class="check_box"></td>
<td class="text-center">Med Assets Company</td>
</tr>
</tbody>
This snippet makes input field in table heading for searching purpose
$('#table2 thead th').slice(3).each(function () {
var title = $('#table2 thead th').eq($(this).index()).text();
$(this).html('<input type="text" placeholder="' + title + '" />');
});
Data Table Initialize
var table = $('#table2').DataTable({
"dom": 'C<"clear">lfrtip',
"sPaginationType": "full_numbers",});
Applying the search
var tableResult = table.columns().eq(0);
if (tableResult !== null) {
tableResult.each(function (colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function () {
table
.column(colIdx)
.sort()
.search(this.value)
.draw();
});
});
}
Please check jsfiddle when check box is checked it totally mess up
https://jsfiddle.net/sxgd0thm/
$('#example').dataTable( {
"aoColumnDefs": [
{ "bSearchable": true, "aTargets": [ 0,1,2,3,4,5 ] }
] } );
Try with "bSearchable" with allowable column search
$('#table2').dataTable({
"dom": 'C<"clear">lfrtip',
"sPaginationType": "full_numbers",
"aoColumnDefs": [
{ "bSearchable": false, "aTargets": [ 0 ] },
{"bSortable": false, "aTargets": [ 1 ]}
]});
Can you try with this

jquery datatable disable sort in specific row

How to disable sorting in specific row/column in jquery datatable using a class?
here's my sample table;
<table>
<thead>
<tr>
<th class="sorting_disabled">Title1</th>
<th class="">Title2</th>
<th class="sorting_disabled">Title3</th>
</tr>
</thead>
<tbody>
<tr><td>Tag 1</td><td>Date 1</td><td>Date 2</td></tr>
<tr><td>Tag 2</td><td>Date 2</td><td>Date 2</td></tr>
<tr><td>Tag 3</td><td>Date 3</td><td>Date 3</td></tr>
<tr><td>Tag 4</td><td>Date 4</td><td>Date 4</td></tr>
<tr><td>Tag 5</td><td>Date 5</td><td>Date 5</td></tr>
....
</tbody>
</table>
script;
$('.sortable thead tr th.sorting_disabled').livequery(function() {
$(this).removeClass('sorting');
$(this).unbind('click');
});
above code works but if I click to the next column who has a sorting its shows again an arrow. though its not clickable ;(
How can I disable the sorting by using a class and not using/redraw a table.
You can disable the sorting using a class in definition.
Just add this code to the datatable initialization:
// Disable sorting on the sorting_disabled class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "sorting_disabled" ]
} ]
$('#example').dataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 1 ] }
]});
That should do it..;)
The only solution:
First add class="sorting_disabled" to any<th> that you want to disable sorting, then add this code to the datatable initialization:
// Disable sorting on the sorting_disabled class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "sorting_disabled" ]
} ],
"order": [
[1, 'asc']
],
As said in the Datatables documentation:
As of DataTables 1.10.5 it is now possible to define initialisation options using HTML5 data-* attributes. The attribute names are read by DataTables and used, potentially in combination with, the standard Javascript initialisation options (with the data-* attributes taking priority).
Example:
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th data-orderable="false">Start date</th>
<th>Salary</th>
</tr>
</thead>
I strongly recommend using this approach, as it is more cleaner than others. DataTables 1.10.15 was originally released on 18th April, 2017.
try the following answer .it works for me.
<table class="tablesorter" id="tmp">
<thead>
<tr>
<th>Area</th>
<th>Total Visitors</th>
</tr>
</thead>
<tbody>
<tr>
<td>Javascript</td>
<td>15</td>
</tr>
<tr>
<td>PHP</td>
<td>3</td>
</tr>
<tr>
<td>HTML5</td>
<td>32</td>
</tr>
<tr>
<td>CSS</td>
<td>14</td>
</tr>
<tr>
<td>XML</td>
<td>54</td>
</tr>
</tbody>
<tfoot>
<tr class="no-sort">
<td><strong>Total</strong></td>
<td><strong>118</strong></td>
</tr>
</tfoot>
source : http://blog.adrianlawley.com/tablesorter-jquery-how-to-exclude-rows
<th class="sorting_disabled"> </th>
$(document).ready(function () {
$('#yourDataTableDivID').dataTable({
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": ["sorting_disabled"]
}
]
});
});
I hope below code works in your case.
$("#dataTable").dataTable({
"aoColumns": [{"bSortable": false}, null,{"bSortable": false}]
});
You need to disable sorting via "bSortable" for that specific column.
$(document).ready(function() {
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false },
null,
{ "bSortable": false }
]
});
});
I came with almost the same solution like in the question, but I used the "fnHeaderCallback". As far as I understood, it gets called after each header redisplay, so no more worries about 'sorting' class that appears again after clicking on column next to target column.
$('.datatable').dataTable({
"fnHeaderCallback": function() {
return $('th.sorting.sorting_disabled').removeClass("sorting").unbind("click");
}
});
Additional documentation about callbacks: http://datatables.net/usage/callbacks
this code worked for me in react.
in row created i added fixed-row class to the row i wanted to stay fixed and not sortable and i drawcallback i hid the row then i appended it to the table itself.
Hope this works for you:
$(this.refs.main).DataTable({
dom: '<"data-table-wrapper"t>',
data: data,
language: {
"emptyTable": "Loading ...",
},
columns,
ordering: true,
order: [0,'asc'],
destory:true,
bFilter: true,
fixedHeader: {
header: true
},
iDisplayLength: 100,
scrollY: '79vh',
ScrollX: '100%',
scrollCollapse: true,
"drawCallback": function( settings ) {
var dataTableId = $("#To_Scroll_List").find(".dataTables_scrollBody table").attr("id");
$("..fixed-row").css('display','none');
$("#"+dataTableId+"_wrapper table").find('tbody tr:last').after($('.fixed-row'));
$(".fixed-row").show();
},
createdRow: function (row, data, index) {
if(data.UnitsPerLine == 999){
$(row).addClass('fixed-row');
}
},
initComplete: function (settings, json) {
$("#To_Scroll_List").find(".dataTables_scrollBodytable").attr("id");
$("#"+dataTableId+" thead tr").remove();
});
DatatableSearch(dataTableId+"_wrapper table", "AverageUnitsPerLineReport");
}
});
}
Without using class, you can follow these steps:
Remove the row which has to remain unsorted from the body of the table.
Include the row to be added in the footer of the table if it is the last row.
I did it including the code below in drawCallback:
drawCallback: function(settings) {
let td = $("td:contains('TOTAL')");
if (td.length) {
let row = td.closest('tr');
let clonedRow = row.clone();
row.remove();
$('table tbody').append(clonedRow);
}
}

Categories