0

The default way of initializing dataTables with javascript sourced data is with the data option and it accepts either an array of arrays or an array of objects as far as I know.

var arrayDataSet = [
    ['Trident', 'Internet Explorer 11', '11'],
    ['Blink', 'Chrome 35', '35'],
    ...
];

var objectDataSet = [
    {
        engine: 'Trident',
        browser: 'Internet Explorer 11',
        version: '11'
    },
    {
        engine: 'Blink',
        browser: 'Chrome 35',
        version: '35'
    }
    ...
];

I want to use the createdRow option though and add for example an id and url on each row. I think I want to initialize with data like this instead:

var otherDataSet = [
    {
        id: 'ie11',
        url: 'http://windows.microsoft.com/en-us/internet-explorer/download-ie',
        data: {
            engine: 'Trident',
            browser: 'Internet Explorer 11',
            version: '11'
        }
    },
    {
        id: 'chr35',
        url: 'https://www.google.com/chrome/browser/',
        data: {
            engine: 'Blink',
            browser: 'Chrome 35',
            version: '35'
        }
    }
];

Is it possible?

1 Answer 1

3

Yes this can be done. You need to set the data property in the columns config object to set where each column should use for it's data. Then you can reference any other fields in the createdRow callback. Here is a working fiddle: http://jsfiddle.net/V7bBg/2/

var otherDataSet = [
    {
        id: 'ie11',
        url: 'http://windows.microsoft.com/en-us/internet-explorer/download-ie',
        data: {
            engine: 'Trident',
            browser: 'Internet Explorer 11',
            version: '11'
        }
    },
    {
        id: 'chr35',
        url: 'https://www.google.com/chrome/browser/',
        data: {
            engine: 'Blink',
            browser: 'Chrome 35',
            version: '35'
        }
    }
];


$(document).ready(function() {
    $('#example').dataTable( {
        "data": otherDataSet,

        //define the columns and set the data property for each column
        "columns": [
            { "title": "Engine",  "data": "data.engine" },
            { "title": "Browser", "data": "data.browser"},
            { "title": "Version", "data": "data.version"}
        ],
        "createdRow": function ( row, data, index ) {
            //adding id and url as attributes to the row
            $(row).attr('id',data.id).attr('data-url',data.url);
        }
    } );            
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.