2
\$\begingroup\$

I am generating a searchable and sortable data table using bootstrap. All works fine.

I am looking for the best approach to get it. Can anyone can please update/suggest the right way, if you find anything better?

jsfiddle

var tableMaker = function (columNames, parent, data) {
    var table = $('<table />', {
        id:"example",
        class:"table table-striped table-bordered"
    })
    .append($('<thead><tr></tr></thead>'))
    .append($('<tbody></tbody>'))
    .append($('<tfoot><tr></tr></tfoot>'));

    var thead = columNames.map(function (item) {
        return "<th>" + item + "</th>";
    });

    var tbody = data.map(function (item, index) {
        var tr = $('<tr />');
        columNames.map(function (label) {
            var label = label.replace(' ', '');
            var labelData = item[label];
            tr.append('<td>' + labelData + '</td>')
        });
        return tr;
    });

    table
    .find('thead tr')
    .append(thead).end()
    .find('tfoot tr')
    .append(thead).end()
    .find('tbody')
    .append(tbody)
    parent.append(table); //appending to parent
    table.dataTable(); //starting tablar data works
};

var initTable = function () {
    var columNames = ['Organization Name', 'ZipCode', 'Telephone' ];
    var data = $.getJSON('https://tcs.firebaseio.com/d/DocPageDetails/d/Organizations.json');
    data.done(function (data) {
        tableMaker(columNames, $('#container'), data);
    });
}

initTable();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.