Datatables vertically scroll to particular row id - javascript

I am using datatables to show data. In my datatables there are some rows which are doubleclick to edit and reload the datatables after success. The problem is when the datatable reloads it goes back to the top of the table but i need to stay at the same row which i was added.
my datatable structure is like this
<table class='table-product' >
<tr id='101'>
<td></td>
</tr>
<tr id='102'>
<td></td>
</tr>
<tr id='103'>
<td></td>
</tr>
<tr id='104'>
<td></td>
</tr>
<tr id='105'>
<td></td>
</tr>
</table>
This is JS function i am using
var table2 = $('.table-product').DataTable({
searching:true,
processing: true,
"language": {
processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw" style="color:#13436c;"></i><span class="sr-only">Loading...</span> '},
colReorder: {
realtime: false
},
ordering: false,
// "aaSorting": [[2,5,14,24]],
retrieve: true,
scrollX: true,
scrollY : '90vh',
scrollCollapse: true,
serverSide: true,
fixedHeader: false,
dom: 'Blfrtip',
"columnDefs": [],
pageLength: {{50}},
lengthMenu: [ 50, 100, 150, 200],
buttons: [
{
extend: 'colvis',
columns: ':not(.noVis)',
}
// {
// extend: 'excelHtml5',
// text: '<i class="fa fa-file-excel-o" style="font-size:22px;" title="Export Excel"></i>',
// exportOptions: { orthogonal: 'export',columns: ':visible' },
// title: null,
// }
],
ajax: {
beforeSend: function(){
$('#loader_modal').modal({
backdrop: 'static',
keyboard: false
});
$("#loader_modal").data('bs.modal')._config.backdrop = 'static';
$("#loader_modal").modal('show');
},
url:"{!! route('some-url') !!}",
data: function(data) { data.default_supplier = $('.default_supplier option:selected').val(), data.prod_type = $('.prod_type option:selected').val(),
data.prod_category = $('.prod_category option:selected').val(),
data.prod_category_primary = $('.prod_category_primary option:selected').val(),
data.filter = $('.filter-dropdown option:selected').val(),
data.sortbyparam = column_name,
data.sortbyvalue = order },
method: "post",
},
columns: [
{ data: 'checkbox', name: 'checkbox'{{#$hide_pricing_columns}} },
......
{ data: 'last_price_history', name: 'last_price_history' },
// Dynamic columns start
],
initComplete: function () {
// Enable THEAD scroll bars
$('.dataTables_scrollHead').css('overflow', 'auto');
$('.dataTables_scrollHead').on('scroll', function () {
$('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
});
},
drawCallback: function(){
$('#loader_modal').modal('hide');
},
});
I have a ID on each row and i want to stay at the same row where I was working. Either i can lock the scroll here or go back to the same row after reloading of datatable.

Related

How to get data values of checked rows of DataTables

I have a DataTables with a checkbox column on the 1st column of the DataTables, I need to get the data value of checked row, so for example:
checkBox simsPid ICCID IMEI
-------- ------- ----- ----
1 98789 AABBCC
x 2 18729 A3B4C5
I need to get the data values of checked row (in my use case above, I need to get simsPid, ICCID, and IMEI)
I have tried codes below, I have got checked rows but I don't have an idea on how to get the value?
I need advice.
$('#sims').DataTable({
destroy: true,
responsive: true,
info: false,
autoWidth: false,
filter: true,
lengthChange: false,
paging: false,
searching: true,
order: [1, 'asc'],
ajax: {
url: '#Models.AppSettings.Path.Deployment' + '/SIM/List/',
dataSrc: ''
},
columns: [
{
'data': null,
'defaultContent': '',
'targets': 0,
'checkboxes': {
'selectRow': true
}
},
{ data: 'simsPid', visible: false },
{ data: 'iccid', className: 'text-left', width: '10%', responsivePriority: 1 },
{ data: 'imei', className: 'text-left', orderable: true, width: '10%', responsivePriority: 2 }
],
dom: '<"card-header border-bottom p-1"<"head-label"><"dt-action-buttons text-end"B>><"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
buttons: [
{
text: 'Set Status',
className: 'btn btn-outline-warning',
action: function(e, dt, node, config) {
var client_table = $('#sims').dataTable();
var rows = $(client_table.$('input[type="checkbox"]').map(function() {
return $(this).prop("checked") ? $(this).closest('tr') : null;
}));
// here I got the rows, but I don't know how to get the value of simsPid. iccid, and imei
$.each(rows, function(index, rowId) {
});
}
},
{
text: 'Discard',
className: 'btn btn-outline-secondary',
action: function(e, dt, node, config) {
}
}
]
});
})

How to deal with null values in JQuery DataTable when using ajax

I'm getting the following error when my page tries to load a DataTable:
DataTables warning: table id=table1 - Requested unknown parameter '0'
for row 0, column 0. For more information about this error, please see
http://datatables.net/tn/4
The table loading works fine when I use a dummy data set of random values, but the data I would like to display has many null values, and this may be why the problem arises. I would like to know how best to set the DataTable settings such that null values are recognized and displayed as an empty string.
I tried adding a render function to solve the issue (adapted from an example described in the comments on datatables oficial forum), but it's not currently working, and I'm not sure how best to implement it, or if it would be better to use another method altogether.
jQuery:
function setupData() {
$(document).ready(function () {
$('#table1').dataTable({
"dom": 'B<clear>frtip',
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"scrollX": true,
"scrollY": true,
"ajax": {
"url": "/index_get_data",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
responsive: true
});
});
}
$(window).on("load", setupData);
html:
<table contenteditable='true' id="table1" class="tableBody dataTable table-striped table-bordered nowrap display" style="width:100%" >
<thead>
<tr>
{% for item in cols %}
<th>{{ item }}</th>
{% endfor %}
</tr>
</thead>
</table>
A render function that I added to the dataTable declaration, but I couldn't get this to work:
"render": function jsRenderCOL(data, type, row, meta) {
var dataRender;
if (data == null) {
dataRender = "";
}
return dataRender;
}
There are over 130 columns (this can be variable), and the data is updated daily, with many columns potentially containing null data. I'd like to find a method to display the data within the dataTable where the columns don't have to be declared explicitly within the dataTable function. Thanks for any help you can provide.
You could try to set the defaultContent on initialisation for each and every column to be an empty string i.e.
$('#table1').dataTable( {
"columnDefs": [ {
"targets": (pass a variable in here that you have calculated based on the number of columns to render)
"defaultContent": ""
} ]
} );
and for the targets attribute pass in a variable that defines the indexes of the columns.
You dont have to worry about ajax data use this code
$('.dataTable').dataTable({
destroy: true,
paging: true,
searching: true,
sort: true,
"ajax": {
url: '{{ url('users/datatable')}}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
'data':{}
},
"columns": [
{data: 'id'},
{data: 'name'},
{data: 'email'},
{data: 'membership_no'},
{data: 'is_active'},
{data: 'varsity_session'},
{data: 'due_amount'},
{data: 'paid_amount'},
{data: 'created_at'},
{data: 'last_transaction_date'},
{data: 'action'},
],
"columnDefs": [
{"bSortable": false, "targets": [1, 6]},
{"searchable": false, "targets": [4, 6]}
],
lengthMenu: [[10, 50, 100, -1], [10, 50, 100, "All"]],
pageLength: 10,
"dom": 'Blfrtip',
buttons: [
{
extend: 'copy',
text: 'copy',
className: 'btn btn-primary',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'csv',
text: 'csv',
className: 'btn btn-warning',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'excel',
text: 'excel',
className: 'btn btn-danger',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'pdf',
text: 'pdf',
className: 'btn btn-success',
exportOptions: {
columns: 'th:not(:last-child)'
}
},
{
extend: 'print',
text: 'print',
className: 'btn btn-btn-info',
exportOptions: {
columns: 'th:not(:last-child)'
}
}
]
});
});
Add
columnDefs:[
{"render":function(data){if(data == "null") {return "-"} else {return data}}, "targets":"_all" },
],

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>

Datatable return [Object Object] on index column

I'm using datatable to show data from controller (i'm using Codeigniter) and need to show number column on the left table column.
I have tried:
$(document).ready(function() {
$('#booking_table').dataTable( {
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth : true,
ajax: {
"url" : base_url+"book/ajax_history",
"type" : "POST",
data : function (d){
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [
{
data : "b.booking_id",
visible : false,
},
{ data : null}, //where i should put index number
{ data : 'b.booking_date', className : "hidden-xs"},
{ data : 'b.from_name', className : "hidden-xs"},
{ data : 'b.to_name'},
],
responsive: false
});
// reference the table in a variable
var table = $('#booking_table').DataTable();
table.on( 'order.dt search.dt', function () {
table.column(0, {
search:'applied',
order:'applied'
}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
My Table:
<table class="table table-condensed" id="booking_table">
<thead>
<tr>
<th class="hidden-xs">id</th>
<th>No</th>
<th class="hidden-xs">
Tanggal
</th>
<th class="hidden-xs">
Pengirim
</th>
<th>
Penerima
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Refer to this https://www.datatables.net/examples/api/counter_columns.html
but, it's not working. What am I doing wrong ?
Please try below mentioned solution. Hope this will help you. Actually you initialized datatable two times.
$(document).ready(function() {
var table = $('#booking_table').dataTable({
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth: true,
ajax: {
"url": base_url + "book/ajax_history",
"type": "POST",
data: function(d) {
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [{
data: "b.booking_id",
visible: false,
},
{
data: null
}, //where i should put index number
{
data: 'b.booking_date',
className: "hidden-xs"
},
{
data: 'b.from_name',
className: "hidden-xs"
},
{
data: 'b.to_name'
},
],
responsive: false
});
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});

Disable selected rows in some rows of dataTable

I use DataTable for create a list. and I unable selected multirow in it.
when click on some first rows (page1 of table), rows was selected. but when click on other pages, rows was not selected and was not go to this script and dont show anything:
$("#example tbody tr").click( function( e ) {
console.log(e);
console.log( $(this).hasClass('selected'));
if ( $(this).hasClass('selected') ) {
console.log(1111111111);
$(this).removeClass('selected');
}
else {
console.log(222222222);
table.$('tr.selected')//.removeClass('selected');
$(this).addClass('selected');
}
});
my table:
Studentjson = {BrowserStats};
var data = jQuery.map(Studentjson.BrowserStats, function (el, i) {
return [[el.imagePath, el.firstName, el.lastName, el.homeLocationText, el.homePhoneNumber,
el.role, el.edit, el.delete]];
});
table = $('#example').DataTable({
"aaData": data,
columns: [
{
"width": "3%",
data: null,
className: "center",
"orderable": false,
defaultContent: '<img class="img-responsive" src="" />'
},
{"width": "27%"},
{"width": "27%"},
{"width": "37%"},
{
data: null,
"width": "3%",
className: "center",
"orderable": false,
defaultContent: '<p data-placement="top" data-toggle="tooltip" title="Edit"><button id="EditStudent" class="btn btn-primary btn-xs" data-title="ویرایش" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>'
},
{
data: null,
"width": "3%",
"orderable": false,
defaultContent: '<p data-placement="top" data-toggle="tooltip" title="Delete"><button id="DeleteStudent" class="btn btn-danger btn-xs" data-title="Delete" ><span class="glyphicon glyphicon-trash"></span></button></p>'
},
{
"visible": false,
"searchable": false
},
{
"visible": false,
"searchable": false
}
]
});
Why this is? What i must do?

Categories

Resources