DataTables not initialising twice on the same page? - javascript

I am trying to use DataTables twice on two different modals, the problem I'm having is the second modal that opens the DataTable isn't being initialised?
CodePen of the process -
http://codepen.io/kieronapple/pen/WwzrgP
How it should work -
First modal opens first DataTables initialises
Press manage on the first modal, second modal opens. But DataTables doesn't initialise?
Function to initialise both tables
function getValidTags(type){
var ruleID = $('.ruleID').val();
switch(type){
case "validTags":
var table = $('.valid-tags').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID,
type: type
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm manageAutofixes" type="button">Manage</button> <button class="btn btn-danger btn-sm deleteValid">Delete</button>';
}
}],
destroy: true
});
break;
case "autofixes":
alert('hi');
var table2 = $('.autofixes-table').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID,
type: type
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm manageAutofixes" type="button">Manage</button>';
}
}],
destroy: true
});
break;
}
}
Function to action first DataTable
$('input[class="val_list"]').click(function() {
$('.ruleID').val($('#mongoid').val());
$('.validation-list-modal').modal('show');
$('.validTagsTable').empty();
if ($('.val_list').is(':checked')) {
$(".tags, .tm-input, .new-tag, .allow_null_div, #null-label, .auto-fix").show();
}
getValidTags('validTags');
});
Function to action second DataTable
$('.valid-tags').on('click', '.manageAutofixes', function(){
$('.autofixes-modal').modal('show');
getValidTags('autofixes');
})

Related

Datatable adding a new row with row.add.draw() but with different content then the other rows

I am trying to add a new row to the datatable loaded by ajax, but need the content of the new row to be different then the previous rows. I am using row.add.draw() and a new row is added to the table but with the same fields as the other rows. I need the new row to have a "ADD" button instead of "EDIT" and "DEL".
Here is the columns of the table in general:
columns: [
{ data: 'mls' },
{ data: 'steet' },
{ data: 'city' },
{ data: 'zip' },
{ data: 'country' },
{'data': null, 'render': function (data, type, row, meta) {
return '<button id="del-'+row.mls+'" class="btn btn-danger btn-xs edit_active" data-title="Delete" data-toggle="modal" data-target="#del" >Delete</button>';
}
},
this is the function of row.add.draw() :
$("#cur_act_tbl").DataTable().row.add({"mls": '',"street": '',"city": '',"zip": '',"country": ''}).draw();
In your data add a type property that will tell DataTables if this is a new row or an existing one. You will need to modify your Ajax return to include this property also (but with the value "existing")
{"mls": '',"street": '',"city": '',"zip": '',"country": '', "type": "new"}
Then in DataTables you just need to check for this property and return the corresponding button.
columns: [
{ data: 'mls' },
{ data: 'steet' },
{ data: 'city' },
{ data: 'zip' },
{ data: 'country' },
{ render: (data, type, row, meta) => {
let btn = '';
if(row.type == 'new') {
btn = '<button id="add-'+row.mls+'" class="btn btn-primary btn-xs edit_active" data-title="Add" data-toggle="modal" data-target="#add">Add</button>';
} else {
btn = '<button id="edit-'+row.mls+'" class="btn btn-info btn-xs edit_active" data-title="Edit" data-toggle="modal" data-target="#edit">Edit</button>';
}
return btn;
}
],

datatable add class a td render

How Can I add a class in this render where I ask if the office is enable or disable, if this disable should add this class table-active. I was searching for some similar question but none worked.
var table = $('#tbl_1').DataTable({
"order": [
[1, "asc"]
],
"destroy": true,
"ajax": {
"method": "POST",
"url": "JSON/Office.php"
},
"iDisplayLength": 15,
"columns": [ {
"data": "Office",
"width": "20%"
}, {
"data": "Status",
"searchable": false,
"sortable": false,
"aling": "center",
"render": function(data, type, row) {
var Status = row["Status"];
if (Status == 'FALSE') {
return '<button class="btn btn-sm btn-success active" onclick="enable_item(this)"title="Active">Active</button>';
} else {
return '<button class="btn btn-sm btn-danger disable" onclick="disable_item(this)" title="Disable"> Disable</button>';
}
}
}],
"dom": '<"dt-buttons"Bf><"clear">lirtp',
"paging": true,
"autoWidth": true,
buttons: [{
extend: 'excel',
text: 'Excel'
}]
});
One of the answer I found was this $(row).addClass("table-active"); but still not working :(. I hope I explain well greetings
If I understood you correct and you want to add a class to the <tr> element you can use the createdRow hook - https://datatables.net/reference/option/createdRow.
$('#tbl_1').dataTable({
"createdRow": function( row, data, dataIndex ) {
if ( data["Status"] == false ) {
$(row).addClass( 'table-active' );
}
}
});

Change only selected row/cell in DataTable

I have this piece of code where table cell is edited and updated.
$.ajax({
url: url_base + 'update',
type: "POST",
data: params,
dataType: 'json', // data type
contentType: "application/json; charset=utf-8",
success: function(res) {
/*var params = {};
callFunction("getWords", params,
function(bSuccess, res) {
$('#example').dataTable().fnDestroy();
var table = $('#example').DataTable({
data: res,
"columns": [
{ "bSortable": false, "targets": 0, "data": 'UserWord' },
{ "bSortable": false, "targets": 1, "data": 'UserWordAlt1' },
{
"targets": 2,
"data": 'UserWord',
"render": function(data) {
return '<button alt="Edit" class="btn btn-primary" value="' + data + '" onclick="edit(this)"><i class="far fa-edit"></i></button> ' + '<button class="btn btn-danger" id=' + data + ' onclick="del(this)"><i class="fas fa-trash-alt"></i></button>'
}
}
],
"order": [
[1, 'asc']
]
});
}
);*/
$('#updateAnliegenModal').modal('hide');
alertify.success('New word updated successfully');
},
error: function(xhr, resp, text) {
console.log(xhr)
}
})
});
The thing is, when I update row I want to affect changes only for that row. Not to refresh the dataTable. In my current case I lost focus from that row which I am updating because table is reloaded again and rows are sorted by new data. Another problem is when I search for a specific word using the search feature of DataTable. If I want to update that found word I want to display only that searched word, not to reload the whole table.
I commented that part where new table is reloading... Actually I am calling again the same getWords function which on success destroys the current datatable and reloads the new one.

How to get row values in Jquery Datatable Render?

Hello guys I am stuck on something I have to get the values of the whole row of data table, as far I am getting id but not getting whole row object
this is where I am
var table = $('.dtPrimaryBottom').DataTable({
// dom: "Bfrtip",
"lengthMenu": [[6], [7]],
paging: true,
columns:[
{ title: 'Student ID', data: 'stu_ID', visible:false},
{ title: 'Registration No', data: 'Registration No' , 'searchable':true},
{ title: 'Name', data: 'Name' },
{ title: 'FathersName', data: 'FathersName' },
{ title: 'Class', data: 'Class' },
{ title: 'Section', data: 'Section' },
{
//"title": "Actions",
//"mdata": null,
//"render": function (data, type, row) {
// return '<button class="btnID">Edit</button>';
//"mData": null,
//"bSortable": false,
//"mRender": function (stu_ID) { return '<input id="btnDispose" type="button" onclick="myfunction(' + stu_ID +')" value="Edit" />'; }
title:'Actions',
'data': 'stu_ID',
'render': function (data, type, row) {
debugger;
var id = $(this).data('stu_ID');
// console.log(data);
return '<input id="btnEdit" type="button" class="btn btn-warning" onclick="myfunction(' + data + ')" value="Edit" /> <input id="btnDelete" type="button" class="btn btn-danger" onclick="myfunction(' + data + ')" value="Delete" />';
}
}
],
data: JsonData
});
on my onclick function when I write data I get the id but when I try to pass the whole row to my function it does not get hit
function myfunction(data) {
debugger;
var stid = row.stu_ID;
var regNo = row
alert(stu_ID);
}
how to pass whole row values when clicking on edit button?
You are specifying explicitly to pass only one value in data object :
'data': 'stu_ID'
So, you need to remove this property if you want to pass complete object to render function.
Change your code to :
'data' : null
or just simply remove this property, as default it would pass complete object then.
title:'Actions',
'render': function (data, type, row) {
debugger;
console.log(data); // you should in console object now
return '<input id="btnEdit" type="button" class="btn btn-warning" onclick="myfunction(' + data + ')" value="Edit" /> <input id="btnDelete" type="button" class="btn btn-danger" onclick="myfunction(' + data + ')" value="Delete" />';
}
Now you can access it in function down:
function myfunction(data) {
debugger;
var stid = data.stu_ID;
}
You can read more in detail about how to use render function here:
https://datatables.net/reference/option/columns.render
You can use the following way to render data. I have always rendered data in serverside processing the following way :
var table= $('.dtPrimaryBottom').DataTable( {
"serverSide": true,
"destroy" :true,
"lengthMenu": [[6], [7]],
"ajax": {
"url": '/reports/getTopPerformerReport',
},
"columns": [
{ "data": "stu_ID" },
{ "data": "Registration No", },
{ "data": "Name" },
{ "data": "FathersName" },
{ "data": "Class" },
{ "data": "Section" },
{ "data": "stu_ID",
"render": function ( data, type, full, meta ) {
return "<img src=\"http://test.com/"+data+"\" style=\"max-width:150px;\">";
}
},
]
});
Hope it helps.

invoke javascript on button click of a datatable row

Im using dataTable and I have the following:
var oTable = $('#example').dataTable({
bProcessing: true,
sAjaxSource: "/Cart/addresses",
'iDisplayLength': 5,
aaSorting: [],
aoColumns: [
{ "mData": "Contact" },
{ "mData": "Address" },
{ "mData": "Postcode" },
{
"mData": null,
"mRender": function (data, type, full) {
return '<button type="button" class="btn btn-success use-address" onclick="doFunction();" role="button" data-adcode="' + full.ADCode + '">' + 'Use Address' + '</button>';
}
}
]
});
I have tried the following, i basically want to be bale to use adcode when the button is clicked:
$('.use-address').click(function () {
var adccode = $(this).data("adcode");
});
function doFunction()
{
var adccode = $(this).data("adcode");
}
This wont work, in firebug it doesnt hit either of these.
Note the datatable is added dynamically (after clicking a button.)
Any ideas why it aint working?
Thanks
Try to use event delegation here:
$('#example').on('click','.use-address',function () {
var adccode = $(this).data("adcode");
});

Categories

Resources