Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "[email protected]", "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.

like image 458
LittleLebowski Avatar asked Mar 02 '13 12:03

LittleLebowski


People also ask

How do I put two data tables on one page?

You just need to follow the example code for the server side processing multiple times... $(document). ready(function() { $('#example'). dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "../examples_support/server_processing.

How many columns can a DataTable have?

The maximum number of columns allowed in a DataSet, across all its tables, is 16,000 columns. According to MSDN DataTable Class "The maximum number of rows that a DataTable can store is 16,777,216"

How many records can DataTable handle?

The maximum number of rows that a DataTable can store is 16,777,216.


2 Answers

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

enter image description here

like image 198
Sruit A.Suk Avatar answered Sep 28 '22 07:09

Sruit A.Suk


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;
}
like image 20
Danny Lacks Avatar answered Sep 28 '22 07:09

Danny Lacks