DataTable rows aren't turning into hrefs - javascript

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>

Related

Colvis doesnt show any of the columns

schedule_Open_Datatable = $("#make_schedule_open_table").DataTable({
columnDefs: [
{ className: "control", orderable: false, targets: 1, width: "5%" },
{ orderable: false, targets: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] }
],
responsive: {
details: {
type: "column",
target: 1,
},
},
//scrollX: true,
buttons: ["copy", "csv", "excel", "pdf", "print", "colvis"],
sPaginationType: "full_numbers",
ajax: {
url: SODUrl,
// our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
dataSrc: "",
},
columns: columns,
rowReorder: { dataSrc: "seq" },
order: [[0, 'asc']],
dom: "<'row'<'col-sm-6'B><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-4'l><'col-sm-4'i><'col-sm-4'p>>",
select: "single",
//ordering: false,
createdRow: function (row, data, dataIndex) {
$(row).attr("data-id", data.id);
},
The colvis button exists on the page but it doesn't want to show the column any of the columns , i have all the links that was required , i tried using the example used on the bootstrap 4 page but still doesnt work.

How can we set fixed width for Query data tables if table has no header

In my project we have a Jquery datatable in which we dont need to show any headers. So i just hide the header like below
<table id="dataTable1" class="ui celled table" style="width:100%">
<thead style="display:none">
</thead>
</table>
But we have some fixed width defined in this table and because of no header the width is not taking based on our settings.
We have setting like below to do the fixed width.
var dataTable1 = $('#dataTable1').DataTable({
paging: false,
dom: 't',
lengthChange: false,
ordering: false,
info: true,
bInfo: false,
autoWidth: false,
searching: true,
serverSide: false,
fixedHeader: false,
fixedColumns: false,
aaSorting: [],
columnDefs: [
{ targets: 0, width: "40%" },
{ targets: 1, width: "40%" },
{ targets: 2, width: "20%" },
{
"defaultContent": "-",
"targets": "_all"
}
],
columns: [
{ data: "Filed1"},
{ data: "Field2" },
{ data: "Field3"}
],
ajax: {
url: dataTable1Url,
type: "POST",
datatype: "json"
}
});
Is there any way to set column width if we dont have any header in datatable. ?
I have tried to remove header using below code but still its removing header and the width which is added into the header is removed and the whole datatable width is kind of broken.
"drawCallback": function() {
$(this.api().table().header()).hide();
}
Added two css class like below
.width-40-percentage
{
width:40%;
}
.width-20-percentage {
width: 20%;
}
Then applied it in the datatable column definition
columnDefs: [
{ targets: 0, width: "40%", className: 'width-40-percentage'},
{ targets: 1, width: "40%", className: 'width-40-percentage'},
{ targets: 2, width: "20%", className: 'width-20-percentage' },
{
"defaultContent": "-",
"targets": "_all"
}
],
Its working fine now.

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

Data Table Row Undefined(DataTables.js)

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>

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