DataTables TableTools not working with two tables - javascript

I am using TableTools and DataTables v1.10 in same page.
My main page has table and empty div for modal.
<div id="resultDiv">
<table id="mainTable"> ... </table>
<div id="detailModal">
<div id="detailModal-content"></div>
</div>
</div>
<script>
$(document).ready(function () {
var mainTable = $('#mainTable').DataTable({
"dom": 'T<"clear">lrtip',
"tableTools": { ... },
"columns": [
{
"data": null,
"render": function(data, type, row, meta) {
return 'Details';
}
},
....
],
........
});
});
function loadDetail(id) {
$.ajax({
async: false,
url: ...,
success: function(respose) {
var tableInstance = TableTools.fnGetInstance('detailTable');
console.log(tableInstance); //null
}
});
}
</script>
Separate detail page has another table which get rendered in detailModal-content div.
<table id="detailTable">
</table>
<script>
$(document).ready(function () {
var mainDetailTable = $jq11('#detailTable').DataTable({
"dom": 'T<"clear">ltipr',
"tableTools": { ... },
..............
});
});
</script>
Here first TableTools of mainTable is working fine but for second table it is not working (I can click button but clicking on it doesn't create xls file). I am trying to solve this by calling fnResizeButtons() after table created as suggested here. But tableInstance is null.
Any suggestion?

From what I can tell you're having problems with TableTools (not the DataTable) not working on the table which is in the modal?
I've had similar issues myself and it's down to the table being initialised when it's invisible and something to do with the Flash, it can be fixed and this is what I used to fix a similar issue with tables on different bootstrap tabs not having functional TableTools except on the table which was initially visible:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target_id = $(e.target).attr("href");
var jqTable = $(target_id).find("table");
var oTableTools = TableTools.fnGetInstance( jqTable[0] );
if (oTableTools != null && oTableTools.fnResizeRequired()){
/* A resize of TableTools' buttons and DataTables' columns is only required on the
* first visible draw of the table
*/
jqTable.dataTable().fnAdjustColumnSizing();
oTableTools.fnResizeButtons();
}
});
Of course, you'll have to grab the table instance on the shown.bs.modal or whatever other event shows your modal but that should fix the TableTools issue.
Hope that helps.

Your function loadDetail() doesn't load response into <div id="detailModal-content"></div>, therefore second table doesn't get initialized.
Corrected loadDetail() function should look something like:
function loadDetail(id) {
$.ajax({
async: false,
url: '/script.php',
data: { 'id' : id },
success: function(response){
$('#detailModal-content').html(response);
}
});
}

watch out if you're table header is already a table,
then use jqTable[1] or even better jqTable.get(1)

Related

JQuery .on('click') is not working with KTDatatable each row edit dropdown menu

Hi I am facing some issue with KTDatatable dropdown edit for each row, datatable.on(‘click’, is not picking my click event, please help.
The click event is from bootstrap dropdown,
My code is as follows
//Datatable code
var KTDatatableRecordSelectionDemo = function() {
//.....
//.....
columns: [{
},
//.....
{
field: 'Actions',
title: 'Actions',
template: function(row) {
return '\\\\\\ Organization Details\class="dropdown-item" href="#"> Location and contact detials\ Tax settings and bank details\ Access rights\class="dropdown-item" href="#" id="one_another"> Profile image and print logo\\\';},}]
and here below the init datatable function
var localSelectorDemo = function() {
var datatable = $('#organizations').KTDatatable(options);
//....
//....
datatable.on('click', '#form_organisation_details', function() {
var dataId = $(this).attr("data-id");
console.log(dataId);
}
}
}
you can't use onClick directly because the table was not initialized instead use something like this to add the click event after the table is loaded.
$(table_id).on('click', '.btn-edit', function(e){
e.preventDefault();
$.ajax({
type: 'get',
url: 'some link here',
success: function (data) {
$("#response").html(data);
},
});
});
and in the table itself use something like this to add the button in the table row
return Datatables::of($data)->addColumn('actions',function($row){
return '<a title="Edit" class="btn-edit"><i class="la la-edit"></i></a>';
})->rawColumns(['actions'])->make(true);
Try to remove dompurify from the build.json config assets. This plugin sanitizes the datatable custom HTML template option.

Datatables has only 10 rows accessible outside the DataTables creation function

I am using Django and in one of my tamplates I use datatables (1.10.19) to display my table data.
This is how my code looks like:
$(document).ready( function () {
table = $('#mytable').DataTable({
"pagingType": "full_numbers",
data: dataSet,
columns: [
{ title: "Naslov zahtjeva" },
{ title: "Datum slanja" },
{ title: "Status" },
{ title: "Rok Izvršenja." },
{ title: "Id zahtjeva" },
],
"fnCreatedRow": function(row, data, index){
$(row).addClass("clickable-row");
$(row).attr('data-href', data[4]);
$(row).addClass("table_row_point");
},
});
Problem occurs at the line -> $(row).attr('data-href', data[4]);
I have a different function that is suposed to use that 'ID' from 'data-href' attribute in order to go to another page like this
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
});
Thing is it works fine for first 10 rows, and when I try 'console.log( this );' I get
Only for the first 10 rows, and it acts like other 3000 don't even exist, I believe it is connected to the default value of 10 rows that appear, but it makes no sense to me for data to be displayed normally, but the 'tr' element not to exist for all, but 10 of them.
Note: When I place this function into DataTable creation code (1st snippet) it shows all the tr elements
$('#mytable tbody').on( 'click', 'tr', function () {
console.log( this );
} );
If someone has any idea it would be much appreciated
fnCreatedRow function is executed everytime datatable creates the <tr> element in the dom. Since you have enabled pagination, function is run only on the <tr> elements created at the time. If you move on to next page, you'll see that console prints next set of rows.
By the way I think createdRow is preferred over old fnCreatedRow naming convention. https://datatables.net/reference/option/createdRow

Javascript on objects don't work in DataTable rows

I just implemented a DataTable in my app, but it seems like javascript doesn't work within the DataTable.
I've attached all code below for better readability.
As you can see, the ccbtn_action="delete" bit is present, but Chrome/IE/FF doesn't seem to want to do anything when the glyphicon is clicked.
This code works perfectly when called from outside the DataTable.
What gives? Is it something to do about JavaScript not being applied to dynamically generated elements?
Thank you!
Here is the Javascript code that doesn't work:
$(document).ready(function(){
// Delete Records
$('[ccbtn_action="delete"]').on('click', function() {
var type = $(this).attr('ccbtn_value_type');
var value = $(this).attr('ccbtn_value_id');
console.log('type=' + type + '&id=' + value);
if (confirm('Are you sure you want to PERMANENTLY delete this record? There is NO TURNING BACK!')) {
$.ajax({
type: 'POST',
url: 'includes/crmcore_action.php?action=cc_delete',
data: 'type=' + type + '&id=' + value,
success:
function() {
$('#cc_pagetop_status').html("<div class='alert alert-success'><strong>Success!</strong> The record was successfully deleted.</div>");
if (type == "company")
{
window.location = "companies_list.php";
}
else
{
location.reload();
}
}
});
} else {
// Do nothing!
}
});
});
Here is the code for the DataTable:
$(document).ready(function() {
var t = $('#DataTable').DataTable({
"order": [[ 1, 'asc' ]],
ajax: {
url: 'includes/dt_ss.php?getwhat=company',
dataSrc: ''
},
columns: [
{data: null},
{"data": null,
"render": function (data, type, row)
{
return ''+data.name+'';
}
},
//{data: 'name'},
{data: 'tel'},
{
"data": "id",
"render": function ( data, type, full, meta )
{
return '<span class="glyphicon glyphicon-remove" ccbtn_action="delete" ccbtn_value_type="company" ccbtn_value_id="'+data+'" data-toggle="tooltip" data-placement="bottom" title="Click me to delete"></span>';
}
}
],
});
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
Since the js looks ok, this is most probably a timing issue. You part of script that binds the events is executed before the actual elements are created.
To fix that, you can:
Make sure the script runs binding after elements creation
Use dynamic binding (like .delegate() http://api.jquery.com/delegate/)
Try delegating your event like this:
$('#DataTable').on('click', '[ccbtn_action="delete"]', function() { ...
My guess is the click event is attached before your ajax request loads the DataTable rows. You can read more here about jQuery event delegation with on(). Specifically:
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
Try like this, but jquery version must be 1.9+
$(document).on('click', '[ccbtn_action="delete"]', function() { // your remaining code

jQuery DataTables duplicates are initially loading

So, adding on to my question from yesterday: jQuery AJAX call function on timeout
Using the first answer from the post from yesterday, the table does indeed reload without refreshing the whole page. It does so after 30 seconds.
But my problem lies before the first refresh...
The page loads, and the records are duplicated. But after the first refresh and every refresh after (unless I manually refresh using F5), everything is fine. No duplicates.
I'm trying to figure out why there are duplicates and how to remove the duplicates upon the page's initial ready event.
Here is the code, starting with the ready event:
$(document).ready(function()
{
$.ajax({
url:'api/qnams_all.php',
type:"GET",
dataType:"json"
}).done(function(response) {
console.log(response.data);
renderDataTable(response.data)
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
});
Here is the function to load the DataTable:
function renderDataTable(data)
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true
});
// then I add the reload function
setInterval( function () {
$dataTable.ajax.reload();
}, 30000 );
});
As stated above, the setInterval function works like how it should. It's just the initial page load is duplicating all of the records.
Does anyone see why and how to fix it?
I think you've got some duplication going on. You don't need to load the ajax flie and then load it again when you set up the DataTable.
Try replacing all of your code with this:
$(document).ready(function() {
// load and render the data
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true,
// the init function is called when the data table has finished loading/drawing
"init": function() {
// now that the initial data has loaded we can start the timer to do the refresh
setInterval(function() {
$dataTable.ajax.reload();
}, 30000);
}
});
});
Calling clear prevents duplicate rows while loading data into table:
$("#checkResourcesButton").click(function() {
$.post("./get/resources", {
featureName: $('#myvar').val()
}).done(function (data) {
var table = $('#table-output').DataTable();
table.clear();
var json = JSON.parse(data);
for (var row in json) {
var nameVal = json[row].Name;
var emailVal = json[row].emailId;
var roleVal = json[row].role;
var startDateVal = json[row].startDate;
var endDateVal = json[row].endDate;
var toAdd =
{
name: String(nameVal),
emailId: String(emailVal),
role: String(roleVal),
startDate: String(startDateVal),
endDate: String(endDateVal)
};
table.row.add(toAdd);
}
table.draw();
});
});

Using autocomplete (Jquery) on AJAX loaded partial view (MVC4)

I've got a view to create Project models which contains (among other things) a table of company-related data.
I've added a button that does an AJAX call to retrieve a partial view and adds it to the table:
$("#addCompanyRoleProject").click(function () {
cache: false,
$.get('CompanyRoleProjectEntryRow', function (result) {
$("#companyTable").append(result); // Add the row to the table
}, "html").done(function (result) {
});
return false;
});
The partial view is a < tr > in wich one of the < td >'s has an input field:
<input class="company-role-project-company" type="text" data-containerPrefix="#ViewData["ContainerPrefix"]" />
I want that input field inside the partial view received by ajax to be an autocomplete (http://jqueryui.com/autocomplete/) so that the user is able to select from a set of options on each < input > for each row of the table.
I can't seem to access the correspondent field on my AJAX call inside the main view. I've tried using "filter()" and "find()" on both the success and done functions.
I could put my javascript code inside the partial view, but it would then be replicated, not to mention possible ID colisions =\
Any ideias on how to achieve this?
EDIT:
I believe I have everything properly referenced in my view:
#section Scripts {
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
<<<< My JS code is here >>>>
}
And in my page's source code I can see:
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
EDIT 2:
I followed Darin Dimitrov's advice and added this on the ajax success callback, after appending the result to the table:
$('input.company-role-project-company', result).autocomplete({
...define source etc...
});
But when I type something in the input field, it behaves like a regular text field...
Is there something wrong in my process of using an ajax call to: request a partial view, append it to the table, make it an autocomplete ?
Try like this inside your AJAX success callback after you append the new partial markup to the DOM:
$('input.company-role-project-company', result).autocomplete({
...
});
I ended up doing it like this:
// Add entry to table
$(function () {
$("#addItemButton").click(function () {
cache: false
$.get('URL.......', function (template) {
$('#table> tbody:last').append(template);
});
return false;
});
});
$(".the-class-used-in-the-desired-field-from-partial-view").live("click", function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: "URL.........", type: "GET", dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { ....... };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
... Do some magic ...
}
});
});
I.E., I bound the autocomplete with a .live function, outside the AJAX.
Probably not the best way, but so far it's working as I want it to, for multiple entries.
Thanks to Darin Dimitrov anyway for pointing me to the right direction with the
$('input.company-role-project-company', result)

Categories

Resources