Data Table Row Undefined(DataTables.js) - javascript

I am trying to access the id of a row inside my DataTables application. When I select a particular row, the row gets selected, after that when I hit the edit button on a menu that I have displayed on the website the id of the row should get passed to a url(which I took off because it was not working so I decided to console.log the info)
The problem is that the row id is coming back as undefined even though I can visually inspect that the id is there.
Here is the code:
$(document).ready(function(){
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
columns: [
{"data": "documento"},
{
"data": "fecha_entrada"
},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
],
// add an id for each generated row:
fnCreatedRow: function(nRow, nData, nId) {
$(nRow).attr('id', nData['pk1']);
}
}); // end of datatable creation
$('#example tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#btnEdit').click(function () {
var selectedRow = table.row('.selected').id();
console.log(selectedRow);
});
});
For the selectedRow to show as undefined it must mean that the id is not being added to the datatable, but I know its there:

The id() method does not read the ID from the DOM. Instead of setting the id manually with the fnCreatedRow function use the rowId attribute. This sets the id Attribute in the DOM as well but also stores it internally for the use with the id() method.
So if you change the Datatables initialisation to something like this, your code works:
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
rowId: "pk1",
columns: [
{"data": "documento"},
{"data": "fecha_entrada"},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
]
}); // end of datatable creation
And below a working sample:
var table = $('#sample').DataTable({
serverSide: false,
searching: false,
rowId: "id",
data: [
{ "id": 5, "column-a": "Sample Data A", "column-b": 10, "column-c": "Lore ipsum" },
{ "id": 6, "column-a": "Sample Data B", "column-b": 5, "column-c": "Ipsum" },
{ "id": 8, "column-a": "Sample Data C", "column-b": 38, "column-c": "Lore" }
],
columnDefs: [
{
targets: 0,
data: "id",
title: "id"
},
{
targets: 1,
data: "column-a"
},
{
targets: 2,
data: "column-b"
},
{
targets: 3,
data: "column-c"
}
]
});
$('#sample tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#edit').click(function () {
var selectedRow = table.row('.selected').id();
alert(selectedRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<button id="edit">Edit</button>
<table id="sample"></table>

Related

Set default value before click event triggers

I have button groups. Once user clicks on the link, it filters value based on the content in the link. By default I added selected class. I want default value of link which contains selected class to be considered for filtering before click event triggers. It works fine when user clicks on c-btn-group but not considers default value when page loads. As of now it shows complete data without filtering when page loads.
<div class="c-btn-group">
<a class="c-btn selected">Large Cap</a>
<a class="c-btn">Small Cap</a>
<a class="c-btn">virginica</a>
</div>
JS
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
Try the below script. Here is demo
Separate out logic of dataTable filtering inside filter function. Get selected text by $('.c-btn-group .selected').text(); and call filter(initialSelectedText);
var myList2;
$.ajax({
url: "https://raw.githubusercontent.com/markwsac/jsonfile/main/jsondata.json",
type: "get",
dataType: 'text',
async: false,
success: function(response) {
if (!response) return;
response = response.slice(0, -1); // trim ";" at the end
window.myList2 = JSON.parse(response);
},
error: function(err) {
console.log(err);
}
});
var myList = window.myList2;
$(document).ready(function () {
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
const initialSelectedText = $('.c-btn-group .selected').text();
filter(initialSelectedText);
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
filter(searchTerm);
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
});
function filter(searchTerm){
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
});
table.draw();
$.fn.dataTable.ext.search.pop();
}
DataTable provides an Option for this. When you are initializing your table, just use the searchCols option which would load the table with the initial search provided. for Example:
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}],
searchCols: [
null,
null,
null,
{ "search": "Large Cap" },
null,
null,
null,
]
})
Here is the link for this option https://datatables.net/reference/option/searchCols
You can also use the libraries own search method rather than implementing it yourself, so instead of writing:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
just write:
table.column(3).search(searchTerm).draw();

How to add class for td in datatable when add row runtime?

I want add class to td when get list data by ajax
Default my code html
<tr>
<td>#fisrt.System_Code.Code</td>
<td>#fisrt.System_Code.Caption</td>
<td class="text-success">#string.Format("{0:N0}", maden)</td>
<td class="text-danger">#string.Format("{0:N0}", den)</td>
<td class="text-warning nrt-bd" dir="ltr">#string.Format("{0:N0}", maden - den)</td>
</tr>
When i want get list data after filtering , i dont know how to add class
$.ajax({
type: 'GET',
url: '/Record_Professor/Search_Budget/',
data: { from: from, to: to },
success: function (results) {
results.forEach(function (item) {
$('#table_id').dataTable().fnAddData([
item.Code,
item.Caption,
item.Maden,
item.Daeen,
item.Balance
]);
});
},
error: function (error) {
alert('error; ' + eval(error));
}
});
"className": "Classname", is used to add class at run time
$('#table_id').DataTable({
data: data2,
"autoWidth": false,
deferRender: true,
pageLength: 10,
responsive: true,
scrollCollapse: true,
select: {
style: 'os',
selector: 'td:first-child'
},
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
"columnDefs": [{
"className": "Classname",
"targets": [5,2,3,4,9,]
}]
});
$('#example').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 3 ] }
]
} );

DataTable rows aren't turning into hrefs

I created a table with DataTables and at first the document titles that were rendered (from a local JSON file) were wrapped around anchor tags and turned into hrefs. I made some changes to my DataTable initialization and added some new columns to my table, and those things might have prevented the doc titles from turning into hrefs. I'm not 100% sure.
Importing table data:
loadTableData() {
$.noConflict();
let tableRes = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": ""
}
});
}
Rendering table:
$('#km-table-id').DataTable({
columns: [
{ data: "Blank" },
{
data: "Titles",
columnDefs: [ // ----- I believe the issue is with this block
{
data: "Path",
ordering: true,
targets: [ 1 ],
render: function(data, type, row) {
return $('<a>')
.attr({target: "_blank", href: row.Path})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
targets: [1]
}
],
},
{
data: "Categories",
searchable: true,
targets: [ 2 ],
visible: false
},
{
data: "Blank"
}
],
data: tableRes,
language: { searchPlaceholder: "Search All Documents" },
lengthMenu: [ 10, 25, 50, 100, 250, 500 ],
order: [],
pageLength: 500,
paging: true,
pagingType: "full_numbers",
responsive: true,
scrollCollapse: true,
scrollXInner: true,
scrollY: 550,
sDom: '<"top">rt<"bottom"flp><"left">' // puts dropdown on bottom
});
HTML snippet:
<table id="km-table-id" class="cell-border display stripe-hover">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Categories</th>
<th>My Favorites</th>
</tr>
</thead>
<tbody></tbody>
</table>

how to add data in datatable?

I am trying to add data dynamically in datatable.I have initialized table on document.ready and created an instance of it.After that, I am trying to add data in the table using instance.
$(document).ready(function() {
//Initialize tooltips
table_sgdFile_list_linked = $('#sgdFile_list_linked').DataTable({
bSort: false,
destroy:true,
bLengthChange: false,
pageLength: 4,
columns: [{
title: "Name"
},
{
title: "Action"
}
]
});
});
I am trying to bind the data
table_sgdFile_list_linked.data(dataSet)
but it is not working.
my_list = $('#my-table-html-id').DataTable( {
"processing": true,
"serverSide": false,
"paging": true,
"bLengthChange" : true,
"bFilter": false,
"pageLength": 10,
"info": false,
"ordering": true,
"ajax": "PATH-OF-MY-API",
"columnDefs": [
{
"render": function ( data, type, row ) {
var html = data + " Modified!";
return html;
},
"orderable": false,
"targets": 1 //Last column
},
],
})
you can try this:
to add 1 row: table_sgdFile_list_linked.row.add(rowJson).draw();
to add multiple rows: table_sgdFile_list_linked.rows.add(rowsJson).draw();
following worked for me :
table_sgdFile_list_linked.clear().draw();
$('#sgdFile_list_linked').dataTable().fnAddData(trHTML);

DataTables - scrollX causing squashed header

So I'm using DataTables with the scrollX parameter set to true, however it's causing the thead columns to collapse.
Note: the datatable is appearing inside a Bootstrap Modal as part of a react project.
How can I resolve this?
When I click on one of the columns, causing it to refresh, it fixes itself. Also, if I remove the scrollX it also doesn't collapse.
Initialisation code:
$('#item-search').DataTable( {
ajax: {
"data": {
type: "map_items",
map_id: this.map_id
},
"dataSrc": (r) => {
console.log(r);
return r.data;
},
type: "POST",
url: "src/php/search.php"
},
autoWidth : false,
columns: [
{
"data": "brand"
},
{
"data": "name"
},
{
"data": "quantity"
},
{
"data": "measurement"
},
{
"data": "type"
},
],
dom: 'rtlip',
language: {
"info": "Showing page _PAGE_ of _PAGES_",
"infoFiltered": ""
},
lengthMenu: [ 1, 2, 3 ],
pageLength: 1,
processing: true,
responsive: true,
scrollX: true,
select: {
style: "multi"
},
serverSide: true
});
In data table initialization include following property.
autoWidth : true
Along with add this
"fnInitComplete": function(oSettings) {
$( window ).resize();
}
"fnDrawCallback": function(oSettings) {
$( window ).trigger('resize');
}
DataTable should be initialized with the following code to achieve horizontal scrolling:
"sScrollX": "100%",
"sScrollXInner": "110%",
"bScrollCollapse": true,
"fixedColumns": {
"leftColumns": 1
}
This work in my angular project
this.dtTarifas = {
scrollX: true,
autoWidth: false,
lengthChange: false,
responsive: false
}
I have in my package.json "angular-datatables": "7.0.0"
$('#DataTableID').DataTable({
//"scrollX": true,
"initComplete": function (settings, json) {
$("#DataTableID").wrap("<div style='overflow:auto; width:100%;position:relative;'></div>");
},
});

Categories

Resources