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]
Related
i'm trying to generate a table with Datatables.
I receive a json from my controller, here a sample:
this json can change (number of columns, name of the columns) and I can build my table with the good number of column and the good name.
My question is:
How can i do to have a dropdown when the "liste" have an array and a simple input when it's null?
Is it even possible?
EDIT :
I forget to explain something. The Json that I receive is a json to build the table not to fill it. So is it possible to do a columnsDef before the datas are in the cell.
EDIT n°2:
I used the solution that I accepted, but the problem was with my json. I tried to send a json to build and a json to fill the table. So I change my json and I send the list of options in the json to fill the table.
Hope it will help other people.
Thanks
Here are two solutions:
1) With a drop-down.
2) With a formatted array (as an alternative).
1) With a Dropdown
The end result looks like this:
The datatables definition is this:
<script type="text/javascript">
var dataSet = { "records" : [
{ "data" : "123456789",
"liste" : null,
"name" : "Nombre Enfants"
},
{ "data" : "5678901234",
"liste" : [ "Oui", "Non" ],
"name" : "Transport"
}]};
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: [
{ targets: [ 0 ],
title: "Data",
data: "data" },
{ targets: [ 1 ],
title: "Liste",
data: function ( row ) {
if (row.liste == null) {
return null;
} else {
return buildDropdown(row.liste);
}
} },
{ targets: [ 2 ],
title: "Name",
data: "name" }
]
} );
function buildDropdown(data) {
var dropdown = "<select>";
for (var i = 0; i < data.length; i++) {
var option = "<option value=\"" + data[i] + "\">" + data[i] + "</option>";
dropdown = dropdown + option;
}
dropdown = dropdown + "</select>";
return dropdown;
}
} );
</script>
It builds a drop-down based on the assumption that a non-null value is an array. This may not always be the case in your data - just an assumption on my part.
2) With a formatted array
Just in case this is also of interest, DataTables has a built-in syntax for formatting array data, so it is displayed in a cell like this:
In this case, you no longer need the drop-down builder function. Everything else is the same as option (1) except for this part:
{ targets: [ 1 ],
title: "Liste",
data: "liste[, ]" },
Specifically, the [, ] notation lets you format the array data.
I mention this only because it lets you display all the array data in the cell, rather than neeeding to click a drop-down. But that is just a suggestion.
You may find that other functions such as searching and sorting are better with this option.
Update
The question has clarified that the table needs to be built dynamically from the data provided in the JSON.
You can pass variables to the datatables initializer - for example:
var col1 = { targets: [ 0 ], title: "Data", data: "data" };
var col2 = { targets: [ 1 ], title: "Liste", data: "liste" };
var col2 = { targets: [ 2 ], title: "Name", data: "name" };
var dynamicCols = [ col1, col2, col3 ];
The above col1 variable defines the title for the column, and where the column will get its data (from the dataSet.data fields).
The dynamicCols variable can then be used in a columnDefs as follows:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: dynamicCols
} );
However, I am not aware of a way to include a function in a columndef, using this approach (for example to present a cell's data as a drop-down, if needed).
There are additional techniques which can be used to make a datatable even more dynamic - several examples are available online - for example here. Without seeing a more detailed example of the JSON being provided, I am not sure if there are any additional suggestions I can make.
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: "-" },
]
I am binding data to jquery datatable in asp.net mvc, i have an anchor tag in one of the columns of the grid where i am accessing / reading row data and sending that data to a javascript function. The problem which i am facing is, i am able read and send row values to the function which are numbers for example ProductID="1" or CategoryID="3" , but if i try to send ProductName="Chai" to the javscript function i get an error in the console, and if i remove the parameter "ProductName" everything works fine and the javascript function also gets triggered.
Following the console error:
"Index:1 Uncaught ReferenceError: Chai is not defined
at HTMLAnchorElement.onclick (Index:1)"
Following is my Code:
var BindDataTable = function (response) {
$("#tbProduct").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "ProductID" },
{ "mData": "ProductName" },
{ "mData": "SupplierID" },
{ "mData": "SupplierName" },
{ "mData": "SupplierCountry" },
{ "mData": "CategoryID" },
{ "mData": "CategoryName" },
{ "mData": "QuantityPerUnit" },
{ "mData": "UnitPrice" },
{
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
}
],
"columnDefs": [
{
"targets": [2],
"visible": false,
"searchable": false
},
{
"targets": [5],
"visible": false,
"searchable": false
}
],
"aaSorting": []
});
}
var EditProduct = function (ProductID, SuppID, CatID,PrdName) {
var url = "/Product/EditProduct?ProductID=" + ProductID + "&SuppID=" + SuppID + "&CatID=" + CatID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
Error:
My suggestion is that instead of playing around with that much string concatenations, what you can do is pass single object to your function and then use the required fields which needs to be passed as ajax call:
"render": function (data, type, full, meta) {
return '<i class="glyphicon glyphicon-pencil"></i>'
}
and in your js function use it :
var EditProduct = function (product) {
var url = "/Product/EditProduct?ProductID=" + product.ProductID+ "&SuppID=" + product.SupplierID + "&CatID=" + productCategoryID + "&ProdName=" + product.Prooductname ;
You can use the following approach in for passing string arguments to a JavaScript function:
<a onclick="javaScriptFunction(#p.ID, '#p.FileName');">#p.FileName</a>
function javaScriptFunction(id, fileName) {
...
}
I have created a query table using data from json.
I am trying to combine two column values in one
but i always get undefined data when i try to combine two columns.
I am not sure what is wrong here.
not sure what is wrong here
$("#submit").click(function(){
var dataTableExample = $('#tbl_jad').DataTable();
$('#tbl_jad').show();
if (dataTableExample != 'undefined') {
dataTableExample.destroy();
}
dataTableExample =
$('#tbl_jad').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "ID"
},
{
"mData": "Position_x0020_Number",
},
{
"mData": "Title"
}, {
"mData": "Type_x0020_of_x0020_Action"
}, {
"mData": "Series"
}]
,
"columnDefs": [
{
"render": function ( data, type, row ) {
return data +' ('+ row[0]+')';
},
"targets": 1
},
{ "visible": false, "targets": [ 0 ] }
]
});
}
});
return data +' ('+ row["ID"]+')'
where ID is the column heading or column name
I'm using the jquery DataTables plugin to display an array of objects. I would like to clear the table and redraw using the changed data. However, the only way I've been able to do that so far is to destroy the table and reinitialize. I'd like to know if there is a simple way to refresh from JS data source. This is what I'm doing, it works but feels wrong...
if (NAMESPACE.table){
NAMESPACE.table.destroy();
}
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
]
});
if you want to clear the data present in dataTable simply call table.clear() it clears all cells in table.
and then add new data using table.row.add().draw();
table.destroy() does not removes data present in cell of table, it only destroys the current instance of dataTable you created.
Make it simpler:
NAMESPACE.table = $('#assets-table').DataTable({
"data": filteredData,
"columns": [
{ "data": "id" },
{ "data": "type" },
{ "data": "city" },
{ "data": "state"}
],
"destroy": true
});