Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am interested in creating a function that creates DataTables dynamically with the Data parameter passed in the function.

Below is what I wrote so far, the DataTables can add rows dynamically, but not the column header - can use some help here (I've read the DT API, but didn't find much help there).

 var table2 = $('#example2').DataTable({
        "paging" : true,
        "ordering" : true,

     });


     // header row
    table2.columns().header(data["header"]).draw();

     // create rows
     for (var prop in data["staff"]) {
        table2.row.add([
        data["staff"][prop].name,
        data["staff"][prop].position,
        data["staff"][prop].office,
        data["staff"][prop].age,
        data["staff"][prop].Start_date,
        data["staff"][prop].salary
        ]).draw();
     }

The Data passed into the function:

var data = {
"header": [
    "Name",
    "Position",
    "Office",
    "Age",
    "Start_date",
    "Salary"
],
"staff": [
    {
        "name": "Tiger Nixon",
        "position": "System Architect",
        "office": "Edinburgh",
        "age": 61,
        "Start_date": "2011/04/25",
        "salary": "$320,800"
    },
    {
        "name": "Garrett Winters",
        "position": "Accountant",
        "office": "Tokyo",
        "age": 63,
        "Start_date": "2011/07/25",
        "salary": "$170,750"
    },
    {
        "name": "Ashton Cox",
        "position": "Junior Technical Author",
        "office": "San Francisco",
        "age": 66,
        "Start_date": "2009/01/12",
        "salary": "$86,000"
    }
]
};
share|improve this question
    
This is not valid JSON, use this to help you: Json Validator –  Matt Webb Dec 5 '14 at 21:04
    
thanks, I've corrected the JSON format. I was a bit hasty when posting my question :) –  TonyGW Dec 5 '14 at 21:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.