Search code examples
javascriptjqueryhtmljquery-selectorsdatatables

Programmatically create tables with jQuery and dataTables


I am using dataTables to render a table programmatically on a Django web app:

jQuery

$(document).ready(function() {
    $("#dynamic0").html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="peak_table_0"></table>');
    $('#peak_table_0').dataTable( {
        "aaData": {{ table_data|safe }},
        "aoColumns": {{ table_headings|safe }}
    });
});

HTML

<div id="dynamic0"></div>

I am going to have many similar tables, where only the data will change, so I would like to automate the table creation. I have tried to put the jQuery initializers in a loop, but in this case the tables don't render: jQuery

$("div1").each(function(index) {
    var table_id = "peak_table_" + index
    $(this).html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="'+table_id+'"></table>');

    $(table_id).dataTable( {
        "aaData": {{ table_data|safe }},
        "aoColumns": {{ table_headings|safe }}
    });
});

HTML

<div1 id="dynamic0"></div1>
<div1 id="dynamic1"></div1>

I'm guessing the selectors are not identified properly. Any suggestions?


Solution

  • The following works. It was missing the '#' in table_id.

    $("div1").each(function(index){
          var table_id = "peak_table_"+index;
          $(this).html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="'+table_id+'"></table>');
          $("#"+table_id).dataTable( {
              "aaData": {{ table_data|safe }},
              "aoColumns": {{ table_headings|safe }}
          });
    });