I am reloading my datatable on 10 second intervals. When a user clicks on a row, that row will highlight. But when the datatable reloads, the highlight is gone.
Here is the shortened code for my datable:
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
});
});
All of the above works exactly how it's supposed to work. I just need to retain the row highlight after the datatable reloads.
Also, I attempted the answer from this post, but I scrapped it as the row no longer highlights.
Kindly update js file with below changes. Below code will save row clicked in global parameter and then focus the clicked row after ajax call.
var gblIndex = 0; //this will save row clicked index
function setFocus(){
$($('#example1 tbody > tr')[gblIndex]).addClass('selected');
}
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
setFocus(); // this will set focus/highlight row
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
gblIndex = $(this).index(); // this will save the index clicked
});
});
You should review their actual selection documentation to manipulate this. This feature is already built in and setup so on ajax.reload() it will keep your selections.
You can apply classes/styling with their methods as well.
https://datatables.net/reference/option/#select
Related
I have here a Datatable with 3 columns: Checkbox, Name, and SSNTIN, when I select rows then click Submit, their SSNTIN will output in '#txtSSNTIN' input field like "1001,1002,1003" but my problem is only the selected rows in the current page of my Datatable are being outputted in the input field, when I go to another page there is an indicator that the other rows from the previous page are still selected but only current page is outputting, please help
Datatable
Namestable = $('#NamesDatatable').DataTable({
'select': {
'style': 'multi',
},
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'render': function (data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="'+data.ssn_or_tin+'">';
}
}],
'order': [[1, 'asc']],
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
data: null,
defaultContent: '',
},
{ "data": "name", "autoWidth": true },
{ "data": "ssn_or_tin", "autoWidth": true }
]
});
Submit Button
$('#btnSubmit').on("click", function (e) {
e.preventDefault();
var searchNames = $('input:checkbox:checked').map(function () {
return $(this).val();
}).get();
$('#txtSSNTIN').val(searchNames);
});
I have done a datatable and custom it's data but when i click the button on the first column, it only works on the first page and cannot click on other forward pages.
$('#tbl').DataTable( {
responsive: true,
data: data1,
autoWidth: false,
"order": [[ 7, "asc" ]],
"iDisplayLength": 5,
"pagingType": "full_numbers",
"dom": '<"top">rt<"bottom"p><"clear">',
"oLanguage": {
"sEmptyTable": "Not Record"
},
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] }
],
"columns": [
{},{"sClass": "dt-body-justify"},{},{},{},{},{},{},{},{}
]
} );
BUT when for the click function in live mode, it still cannot work
$('#tbl tbody tr #edit_current_product').delegate('a', 'click', function () {
.......
} );
id's must be unique. We dont know your markup but
$('#tbl tbody tr #edit_current_product').delegate('a', 'click', function ()
seems utterly wrong. Either you have multiple <a>'s with the same id #edit_current_product or the right thing actually happens, you have paginated away from the page where #edit_current_product is present.
I guess that what you really want is
$('#tbl').on('click', 'tbody tr a', function()
or use a class instead of an id
$('#tbl').on('click', 'tbody tr .edit_current_product', function()
BTW, why
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] }
],
"columns": [
{},{"sClass": "dt-body-justify"},{},{},{},{},{},{},{},{}
]
you just need
"columnDefs": [
{ "visible": false, "targets": [ 6,7,8 ] },
{ "sClass": "dt-body-justify", targets : [1] }
]
I'm using jQuery DataTables with ajax sourced data.
I have to keep the data up to date every 30 seconds without refreshing the page, and ajax.reload() is the function that I need.
I put ajax.reload() inside a setInterval function.
And all works right (if you stay on page 1). But when you surf the table on page 2 or 3, when setInterval is fired, it gets you back to the page 1.
So ...
Looking to docs at this url: http://datatables.net/reference/api/ajax.reload()
if I pass "false" as second parameter it holds the current paging position, and paging is not reset on reload. BINGO!
It works! BUT ... I have a new problem that a tried to solve the all day and now I'm stuck. That's why I post this question.
It keeps paging but if you are not on page 1, every time that ajax.reload() is fired, the page scrolls (jump directly) to the bottom.
It's very unfriendly, unreadable, unusable.
I don't know WHY the page scrolls to the end-bottom.
I post a link to my simple datatable js that I use on my page.
jsfiddle
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
My solution:
"fnDrawCallback": function(data) {
$(".paginate_button > a").on("focus", function() {
$(this).blur();
});
}
jacopo.galli's solution was very clunky when I implemented for my table, but it's probably because my code was a mess. The idea of adding blur() is great thou.
I rewrite his code a bit:
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
The buttons on the pagination bar will be "unfocused" once the page scrolls.
So your final code should look like this:
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
I've found a solution that works for me.
The problem was the "focus" on DataTables pagination links.
When user clicks on a link page, it sets a focus on that link and when ajax.reload() is fired the browser gets you where the focused element is. My table is the last element of the page so the page scrolls to the bottom.
I got it when I clicked on another area of the page after clicked on page 2 link. The "jumping" problem was gone.
So, I solved firing a blur() when DataTables has complete its initialization and when ajax.reload() has finished (thanks to the first parameter that allows you to define a function).
In DataTables options I added this:
"initComplete": function(settings, json) {
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
},
and then, in setInterval:
setInterval(function(){
datatable.ajax.reload(function(){
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
}, false);
}, 30000);
Don't know if this is the "best solution" ... but it works and could helps someone.
want to add HTML.actionlink to Jquery Datatable.
Am wokrking on this existing site made by someone else. For adding data they used Jquery Datatable with is new to me.
This is the data table:
this.oUserList = $('#UserList').dataTable({
"bLengthChange": false,
"bSort": true,
"bRetreive": true,
"bDestroy": true,
"aaSorting": [[0, "asc"]],
"bProcessing": true,
"sAjaxSource": "#Url.Action("GetUsers","Users")",
"sAjaxDataProp": "Result",
"aoColumns": [
{ "mDataProp": function(source, type, val) {
return source.FirstName + ' ' + source.LastName;
}, "bSortable": true },
{ (1st column },
{ 2ndcolumn},
{
3rd column
}, "bSortable": false },
{
4th column
}, "bSortable": false
},
{
5th column
}, "bSortable": false
},
Here is where i want to change it to action link
{ (6th)
"mDataProp": function (source, type, val) {
return M2.JsonDateToString(source.DateLastLogin);
}, "bSortable": false
},
My 6th column is a duplicate of the 5th, but what i need here is an action link, like this: (How i normally implement them):
<td>#Html.ActionLink("Edit Roles", "Edit", "Users", new { userName = "User\\" + u.UserName }, new { #class = "action" }) </td>
So what I want to no is how do you add a html actionLink to a Jquery Datatable.
Use the source json object to build the anchor:
this should work
{
"mDataProp": function (source, type, val) {
return 'Edit Roles'
}, "bSortable": false
},
Use this article www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
I'm sure there are a few (better) ways to do this, but I can't get any way to work. I'm trying to have datatables load new data (from different data source) when a button is clicked.
Here's what I have:
$(document).ready(function() {
$('#datatable2').dataTable( {
"ajax": {
"url":"simple4.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
});
The initial table (from simple4.php) loads fine. I'd like it to change when I click on a button (with id=option2 in this case), but nothing happens when I click the button.
Just in case, here's the button code in case I'm missing something obvious:
<label class="btn btn-default">
<input type="radio" name="options" id="option2" value="1" autocomplete="off"> Compare 1 and 2
</label>
Not sure what the issue is. Any insight would be helpful.
UPDATE: see answers below explanation of the issue. One thing I didn't do, which apparently makes a major difference is using "dataTable" versus "DataTable". You need a capital D and capital T. Here's the fixed code that's working now:
$(document).ready(function() {
var table = $("#datatable2").DataTable({
"ajax": {
"url":"simple3.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
});
One more thing...my function that was supposed to fire when I clicked on my radio button wasn't working. Had to change from this:
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
To this:
$('input[id=option2]').change(function(){
table.ajax.url( "simple4.php" ).load();
});
First, as the others have said the variable 'table' is not set.
Second, when you call
var table = $('#datatable2').dataTable({.....})
You are returning a jQuery object that won't have access to any of the DataTables API
To get a DataTables API instance you need to make a call like this:
var table = $('#datatable2').DataTable({....});
This should work, assuming that your data returned by your url is properly formed.
Source: https://datatables.net/faqs/#api
I can't try this now, but I think it gonna work:
var table = $('#datatable2').dataTable({...});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
you are not setting var table = ... so when you call table.ajax... table var does not exists