IF else like at datatable jquery - javascript

How could I perform If else like method in datatable? The variable 'data' returns the value of the variable, which is correct, but if it is blank, it would return the word "from1", "from2" which is supposed to be the value of the variable "from1". Am I doing the right approach or do you have any suggestion as workaround in this problem? thank you for your answers. here is my code:
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
defaultContent: 'from1'
}, {
data: "fdDateTo2",
defaultContent: 'from2'
}, {
data: "fcTrainor2",
defaultContent: 'train1'
}, {
mData: 'dur'
}]
});

I'd use the render option for the column data that you have, its much more flexible in terms of wanting something to be displayed by default.
var table = $('#records').DataTable({
type: 'post',
"ajax": "getHumanTrainings",
"bPaginate": true,
"bProcessing": true,
"pageLength": 10,
"columns": [{
mData: 'tdesc'
}, {
data: "fdDateFrom2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from1>]; // Just use the index for from1
}
// If not blank display data normally
return data;
}
}, {
data: "fdDateTo2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for from2>]; // Just use the index for from2
}
// If not blank display data normally
return data;
}
}, {
data: "fcTrainor2",
render: function(data, type, row) {
// Check if blank
if (data === "") {
return row[<index for train1>]; // Just use the index for train1
}
// If not blank display data normally
return data;
}
}, {
mData: 'dur'
}]
});
I've left comments to give you a guide since I'm not familiar with your data, I would suggest printing out your row first over at render so you'd know which index to use.

Related

Set default value before click event triggers

I have button groups. Once user clicks on the link, it filters value based on the content in the link. By default I added selected class. I want default value of link which contains selected class to be considered for filtering before click event triggers. It works fine when user clicks on c-btn-group but not considers default value when page loads. As of now it shows complete data without filtering when page loads.
<div class="c-btn-group">
<a class="c-btn selected">Large Cap</a>
<a class="c-btn">Small Cap</a>
<a class="c-btn">virginica</a>
</div>
JS
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
Try the below script. Here is demo
Separate out logic of dataTable filtering inside filter function. Get selected text by $('.c-btn-group .selected').text(); and call filter(initialSelectedText);
var myList2;
$.ajax({
url: "https://raw.githubusercontent.com/markwsac/jsonfile/main/jsondata.json",
type: "get",
dataType: 'text',
async: false,
success: function(response) {
if (!response) return;
response = response.slice(0, -1); // trim ";" at the end
window.myList2 = JSON.parse(response);
},
error: function(err) {
console.log(err);
}
});
var myList = window.myList2;
$(document).ready(function () {
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
const initialSelectedText = $('.c-btn-group .selected').text();
filter(initialSelectedText);
$('.c-btn-group').on('click', 'a', function(event) {
var searchTerm = this.textContent;
/* 4th column filtering */
filter(searchTerm);
// Add or remove 'selected' class;
event.preventDefault();
$('a').removeClass('selected');
$(this).addClass('selected');
});
});
function filter(searchTerm){
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
});
table.draw();
$.fn.dataTable.ext.search.pop();
}
DataTable provides an Option for this. When you are initializing your table, just use the searchCols option which would load the table with the initial search provided. for Example:
table = $("#mfTable").DataTable({
data: myList,
paging: true,
lengthChange: false,
searching: true,
info: false,
columns: [
{ data: 'Fund Name' },
{ data: 'Morningstar Rating' },
{ data: 'Category Rank' },
{ data: 'Category' },
{ data: 'Expense Ratio' },
{ data: 'AUM (Cr)' },
{ data: 'NAV' },
],
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}],
searchCols: [
null,
null,
null,
{ "search": "Large Cap" },
null,
null,
null,
]
})
Here is the link for this option https://datatables.net/reference/option/searchCols
You can also use the libraries own search method rather than implementing it yourself, so instead of writing:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
if (data[3] == searchTerm) {return true;}
return false;
})
table.draw();
$.fn.dataTable.ext.search.pop();
just write:
table.column(3).search(searchTerm).draw();

datatables selected row get undefined value

i'm pretty new using datatables and amaze with good fiture in datatables for handling a lots of data. i have read the documentation but still don't get the answer, too much example make me confuse which one is fit for my problem.
so, i trying to generated button which can edit value of selected row, but i think to complex for doing a button each row, i made it more simple with hyperlink text generated each button and can edit selected row which taken the ID of selected row.
The problem is when i succeed with generating link each row, the id of row is undefined.
on comment code name try 1, my table not showing and keep processing for long time
and comment code name try 2, my table working but when i hit edit the value is undefined.
here is my code :
$(document).ready(function(){
var dataTable = $('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
var gender = $('#searchByGender').val();
var name = $('#searchByName').val();
data.searchByGender = gender;
data.searchByName = name;
}
},
'columns': [
{ data: 'id' },
{ data: 'nama' },
{ data: 'grade' },
{ data: 'dept' },
{ data: 'id' },
{ data: 'id',
render: function(data, type, row, meta)
{
//try 1 :
//var data = table.row( this ).data().id;
//return 'edit';
//try 2 :
//var i = row[0];
//return 'edit';
}
},
]
});
undefined ID Image, and
normally this should be ID ie:2200085 not undefined.
any help would be appreciated, sorry if the question just hit little scope but i think out there many people have same problem like me. Thankyou.
you are missing one step after columns[].
$(document).ready(function(){
var dataTable = $('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
var gender = $('#searchByGender').val();
var name = $('#searchByName').val();
data.searchByGender = gender;
data.searchByName = name;
}
},
'columns': [
{ data: 'id' },
{ data: 'nama' },
{ data: 'grade' },
{ data: 'dept' },
{ data: 'id' },
{ data: 'id',
render: function(data, type, row, meta)
{
//try 1 :
//var data = table.row( this ).data().id;
//return 'edit';
//try 2 :
//var i = row[0];
//return 'edit';
}
},
],
createdRow: function ( row, data, index ) {
$(row).attr('title','Category ID : '+data[0]);
$(row).attr('id',data[0]);
$(row).click(function(){
alert(this.id+' is clicked');
});
}
});

Trying to access dataTable variable outside ajax is giving undefined

I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};
You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});

Tabbing doesnt work for datatable

I m using jquery datatables in many pages and its working good in every page and in a single page its not working properly, i mean when i use tab to go through datatable, it works fine for the first time and when i try to do the same for second time, if i try to focus on any thing in few seconds in data table, the focus disappears and the foucs starts from the starting of the page.
Here goes the code
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
}else{
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
// table.destroy();
$("#auditTable tbody").empty();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}
I think the problem is because the datatable instance is not destroyed.
Since datatables saves all the nodes into an object and renders it when ever it wants, emptying the tbody doesnt do anything. it just removes the elements in the page which can be re-drawn/re-rendered by datatable from its stored object.
You can check if the object is already initialized and the destroy it before re-initializing.
if(typeof table != "undefined")
table.destroy();
So the final code will look something like
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
} else {
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
if(typeof table != "undefined")
table.destroy();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}

jQuery DataTables loads data from controller but does not display it

In short, I'm loading a list of clients (as JSON) from an MVC controller. I've verified that the data is structured properly, as well that it does get to the client. The only disconnect is that once the data is loaded, DataTables never displays it.
Here's the JavaScript that initializes the table. I'm almost positive it's configured correctly.
I use the dataSrc parameter to execute some extra code before the data is drawn. Note that it is being executed. I've stepped through just about every piece of this.
I also confirmed that $("clients table") finds the correct element.
$clientsTable = $("#clients table").DataTable({
deferRenderer: true,
info:true,
lengthChange: true,
lengthMenu: [25, 50, 75, 100],
processing: true,
saveState: true,
serverSide: true,
ajax: {
url: "LeadScatter/Clients",
type: "GET",
data: function (d) {
$.extend(d, { byPartner: $("#byPartner").val(), byEnabledDisabled: $("[name=byEnabledDisabled]:checked").val() });
},
dataSrc: function (data) {
getTabState("clients").isLoaded = true;
$("#clients .tab-content").fadeIn(_fadeTimeInMs);
$("#clients .dataTables_filter [type=search]").focus();
return data;
},
error: function (response) {
getTabState("clients").isLoaded = false;
selectedClient = undefined;
$("#tabs").tabs({ disabled: defaultDisabledTabs }).tabs("option", "active", 0);
updateSelectedClient();
showTabLoadError("clients", response.statusText);
if (response.status == 403) {
alert(response.statusText, response.status);
$("#clients").find(".dataTables_empty").text("Sorry, but you do not have permission to view Clients.");
}
}
},
columns: [
{ data: "cakeName", className: "button-cell client" },
{ data: "rpls", className: "number-cell" },
{ data: "forcePayoutIncrease", className: "number-cell" },
{ data: "allocation", className: "number-cell" },
{ data: "inMonthCap", className: "number-cell" },
{ data: "inMonthCapType", className: "number-cell" },
{ data: "toggle", className: "button-cell" },
{ data: "pushToDemo", className: "button-cell" }
]
});
Here's the object that DataTables is picking up. I removed extra array elements to save space. Trust that they're constructed correctly:
{
"draw": 1,
"recordsTotal": 784,
"recordsFiltered": 0,
"data": [
{
"id": 7689,
"cakeName": "<input type='radio' name='selected-client' value='7689' data-id='7689' data-cake-name='aa_test1' data-grouping-id='6666' id='selected-client-aa_test1' class='' /><label for='selected-client-aa_test1' class='disabled'>aa_test1</label>",
"rpls": 40,
"forcePayoutIncrease": 0,
"allocation": 0,
"inMonthCap": 0,
"inMonthCapType": "None",
"enabled": true,
"toggle": "<button type='button' class='button toggle' onclick='toggleClientEnabled(7689);'>Disable</button>",
"pushToDemo": "<button type='button' class='button' onclick='pushClientToDemo('aa_test1');'>Push To Demo</button>"
},
....
]
}
DataTables correctly updates the draw parameter with each subsequent request. Everything behind-the-scenes seems to work fine. Here's the HTML table where the data should be rendered:
<table border="1">
<thead>
<tr>
<th>CakeName</th>
<th>RPLS</th>
<th>ForcePayoutIncrease</th>
<th>Allocation</th>
<th>In-Month Cap</th>
<th>In-Month Cap Type</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
And finally, a screenshot of the table. It's initialized but no data is rendered. You can even see that it's getting the "recordsTotal" variable from the returned object and setting it in the footer.
Am I missing something obvious?
Well, this was frustrating to discover, but it turns out that the dataSrc function was causing it.
I missed in the documentation that when using that parameter as a function, you must return the collection of data that's being displayed, not the JSON object as a whole.
So this:
dataSrc: function (data) {
return data;
}
becomes this:
dataSrc: function (data) {
return data.data; //access the data variable from the returned JSON
}
Voila.

Categories

Resources