Add link to Ajax sourced data in jQuery Datatables - javascript

I want to add a link/href to the 2nd column (the one with "C" data in it). I have tried the columns render function but it only has data of the current column.
https://datatables.net/reference/option/columns.render
I want to use data from different columns onto anchor tag of column 2
this guy here
https://stackoverflow.com/a/47696609/11575565
explains using rowID which would've solved my problem but this isnt working.
I tried using $.getJSON and append() over ajax function but it doesnt work as well.
$(document).ready(function() {
var table = $('#bla').DataTable({
"ajax" : "blist.json",
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C" },
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
],
[the array in blist.json has data "A","B","C","D","E"]

Say, your Link value is in key E then, you would be able to use render as shown below.
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
]

Related

Conditional checking of "datatable checkboxes" in jQuery

Hi I'm trying to create a table that consists of checkboxes. And each row has its own class and ID.
$('#niisPrprtyCoverageTable').dataTable({
"data" : coverageList,
"columns" : [ {
"data" : "seqNo",
"visible" : false
}, {
"data" : "coverageCode"
}, {
"data" : "coverageName"
}, {
"data" : "coverageCode",
"width" : "80px",
"className" : "text-center",
render : function(data, type, row) {
var arrData = data.split(";");
var coverageCd = arrData[0];
var coverageRel = nvl(arrData[1], coverageCd);
data = '<input class="'+coverageRel+'" id="'+coverageCd+'" type="checkbox" onClick="addToArray('
+ coverageCd
+ ','
+ coverageRel
+ ')">';
return data;
}
} ],
"searching" : false,
"bLengthChange" : false,
"iDisplayLength" : 15 ,
"bSort" : false,
"columnDefs" : [ {
"targets" : [ 1, 2 ],
"className" : "left"
}, {
"targets" : [ 2 ],
"width" : "150px",
}, {
"targets" : [ 1 ],
"width" : "100px",
}, {
"targets" : [ 3 ],
"width" : "50px",
"className" : "text-center"
} ]
});
niisPrptyCoverageTable = $('#niisPrprtyCoverageTable').DataTable();
$('#select-all').on('click', function(){
alert('ss');
// Get all rows with search applied
var rows = niisPrptyCoverageTable.rows({ 'search': 'applied' }).nodes();
// Check/uncheck checkboxes for all rows in the table
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
What should happen is, if I check the main row, all the rows under his 'code or id' should be checked also.
It works but only on the first page
but doesn't work on the second page of the datatable
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Use $() API method to get access to elements on all pages, not just current page.
For example:
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
niisPrptyCoverageTable.$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Alternatively see jQuery DataTables Checkboxes extension for easier handling of checkboxes in a table powered by jQuery DataTables.

JsTree-grid doesn't display the data

I'm working with the JsTree Ajax lazy load feature and to display the data I am using JsTree-grid. However, I am having the issue with display the data using the JsTree-grid on the second column. I've the following JSON data that I'm passing through the PHP using the JsTree ajax lazy load feature:
[
{
"id": ​157749,
"parent": "Sheet1.worksheet1webs44lx8GbsHu9igMc2vM_qWJqhePuo257PKZm_6Uo",
"text": "Script 1: Login",
"data": {
"status": "Fail"
}
},
{
"id": ​104511,
"parent": "Sheet1.worksheet1webs44lx8GbsHu9igMc2vM_qWJqhePuo257PKZm_6Uo",
"text": "skip",
"data": {
"status": "Pass"
}
}
]
In the Javascript I've the following code:
$('#jstree').jstree({
plugins: ['grid'],
'grid': {
'columns': [
{
'width': 50,
'header': 'Nodes'
},
{
'width': 30,
'header': 'Status',
'value': function (node) {
return (node.status);
}
}
]
},
'core' : {
'data' : {
"url" : function (node) {
return node.id === '#' ? 'node' : 'tree/' + node.id;
},
'data' : function (node) {
return { 'id' : file.id, 'title' : file.title };
},
"dataType" : "json"
}
}
});
Note: When I console log the node on here: 'value': function (node) { console.log(node); } I got the following result on the console:
Object { status: "Fail" }
Object { status: "Pass" }
I would like to display the status Pass or Fail on the second JsTree-grid column. However, the JsTree-grid isn't displaying the data and I'm even not getting any error on the console. Please, can someone help me regarding what I want to achieve.
I see two issues here:
"parent": "Sheet1.worksheet1webs44lx8GbsHu9igMc2vM_qWJqhePuo257PKZm_6Uo"; your json doesn't have any parents for these nodes
you don't need function here - 'value': function (node) { return (node.status); }, simply use 'value': 'status'.
After fixing these two issues it works, check demo - Fiddle.

How to remove selected existing data and add new row without affecting other rows in Jquery data table

I have 100 rows of data, i want to remove selected data based on ID and add new row for that ID. I want to edit the rows based on ID.
Here is my code:
oCustomization : {
sExportFunctionCall : oMapUrls.exportLiveFleetReport,
bAdvanceExport : true,
bShowDefaultAll : !bLivePaginate
},
pageLength : !bLivePaginate ? -1 : Global.rowLength,
scrollCollapse : false,
scrollY : iDataTableHeight,
serverSide : bLivePaginate,
order : [ [ 3, "desc" ] ],
columns : [
{
"data" : "trackeeName",
"width" : aColumnWidths[0],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeVehicleItems || [], request.term));
}
},
"render" : function(value, type, rowData) {
//Some code here
}
},
{
"data" : "firstName",
"width" : aColumnWidths[1],
"class" : "no-word-break",
settings : {
source : Global.getDriverSuggestion
},
"title" : jQuery.i18n.prop("driver.title.txtInfo"),
"visible" : Global['show.driver.in.reports'] == 1,
"render" : function(value, type, rowData) {
return getUserName(rowData.firstName, rowData.lastName);
}
},
{
"data" : "groupName",
"width" : aColumnWidths[2],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeGroupItems || [], request.term));
}
},
"title" : jQuery.i18n.prop("vehicle.col2label")
},
{
"data" : "dateAndTime",
"width" : aColumnWidths[3],
"searchable" : !bLivePaginate,
"class" : "wordBreak",
"title" : jQuery.i18n.prop("report.columnTitle.date"),
"render" : function(value, type, rowData) {
if (type == "display") {
return rowData.formattedDate;
}
return value;
}
}
I get data in JSON format. I want to remove selected rows , it should not affect other rows data.
Simply use WHERE
DELETE FROM DBNAME WHERE ID=XXX
then Insert into the table with that ID
however, if you want to delete and insert together always, an UPDATE query will work better

How to check for a specific value in an array of object and apply actions only to that object value

I have an array of objects. I'm trying to check for a specific value on an object in the array and show particular fields only for that object.
{
"data" : {
"items" : [ {
"name" : "Basic Week",
"id" : "WK2"
},
{
"name" : "Basic month",
"id" : "WK1"
},
{
"name" : "Basic subscription",
"id" : "11"
},
{
"name" : "all time subscription",
"id" : "11"
}]
}
}
Here I'm trying to check for a string that contains "subscription", so when I make a check, it should return me 2 objects:
{
"name" : "Basic subscription",
"id" : "11"
},
{
"name" : "all time subscription",
"id" : "11"
}
Here is how I'm doing it:
$.ajax("/api/1.0/getData",{
success: function (data) {
lists = data.filter(function (item) {
if(item.name.indexOf("subscription")){
$("#some_div").show();
}else{
$("#some_div").hide();}
});
}
});
html:
<input type="text" id="some_div" style="display:none;"/>
But in the above case it shows the div for the all the objects, where as I would like to show the div only for the value that contains the string "subscription".
EDIT--------
$.ajax("/api/1.0/getData",{
success: function (data) {
lists = data.data.items.filter(function (item) {
if(item.name.indexOf("subscription")> -1){
$("#some_div").show();
}else{
$("#some_div").hide();}
});
}
});
the above edited code still hides the id= "some_div" for all the objects.
var temp = {
"data" : {
"items" : [ {
"name" : "Basic Week",
"id" : "WK2"
},
{
"name" : "Basic month",
"id" : "WK1"
},
{
"name" : "Basic subscription",
"id" : "11"
},
{
"name" : "all time subscription",
"id" : "11"
}]
}
};
console.log($.grep(temp.data.items, function(element){
return element.name.indexOf('subscription') > -1;
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Since you are trying to search inside the items array, the data variable in the success callback is not the array you should filter.
Considering the structure of the object, you should access the array through: data.data.items.
So, try to put this in your success function:
success: function (data) {
data.data.items.forEach( function (item) {
if (item.nome.contains("subscription")) {
$('#some_div').show();
} else {
$('#some_div').hide();
}
});
}
--EDIT
You also need different id attributes for your HTML elements.
Like this:
<input type="text" id="some_div_0" style="display:none;"/>
<input type="text" id="some_div_1" style="display:none;"/>
<input type="text" id="some_div_2" style="display:none;"/>
<input type="text" id="some_div_3" style="display:none;"/>
And then you should use some attribute of your objects inside your array to show or hide each one.
Here, I am using the position of the object in the array to show or hide the correspondent HTML element:
success: function (data) {
data.data.items.forEach( function (index, item) {
if (item.nome.contains("subscription")) {
$('#some_div_' + index).show();
} else {
$('#some_div_' + index).hide();
}
});
}

How to put multiple data in a datatable column?

I'm using Datatables to represent data from a JSON.
My JSON is as follows:
[{"name": "John Doe", "email": "john#gmail.com", "address" : "blah"}]
In Datatables I can easily show these 3 pieces of info in 3 diff columns using the following:
columnDefs = [
{ "mData": "name", "aTargets":[0] },
{ "mData": "email", "aTargets":[1] },
{ "mData": "address", "aTargets":[2] }
];
But the problem is that I want to show "name" and "email" in 1st column and then "address" in the 2nd column.
How can I do that? Please guide.
to make it more short, you can write it like this
"aoColumns": [
{ "mData": "i_id" },
{ "mData": "i_name" },
{ "mData": function (data, type, dataToSet) {
return data.i_id + "<br/>" + data.i_name;
}}
],
and the result
columnDefs = [
{
data: {name : "name", email : "email", address : "address"},
mRender : function(data, type, full) {
return data.name+' '+data.email+' '+data.address;
}
}
];
The above code can render multiple data in a column of a datatable.
Rather than putting either the name or e-mail in the first column in the column definition, you can use a function to get and print whatever data you want. See the mData section on this page for more details: https://datatables.net/usage/columns. In my example below I use aoColumns because I tested my answer that way; but in the link referenced they used aoColumnDefs and provide elaboration on the type and dataToSet fields. This approach should hopefully help anyone reading this answer whether you use aoColumns or aoColumnDefs.
For example, using aoColumns rather than aoColumnDefs:
aoColumns = [
{ "mData": getNameAndEmail },
{ "mData": "address" }
];
Then define the getNameAndEmail function in JavaScript scope which takes three parameters: the data passed back, the type of action on the data, and if the type is "set" then the data to set.
function getNameAndEmail(data, type, dataToSet) {
return data.name + "<br>" + data.email;
}
[You can use syntax like this:
It worked for me.]
"columnDefs":[{
"targets":0,//column index
"data":"first_name",
"render":function(data,type,row){
return data+' '+row['last_name'];
}
}]
[thanks]

Categories