Dynamically create

by Hifni Nazeer

HTML

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<div>
  <table id="mainTable" border='1'>
    <thead>
      <tr>
        <th>
          <input type="button" value="Upto LKR 2.5 Mil" id="btn1" />
        </th>
        <th>
          <input type="button" value="LKR 2.5 Mil to 5 Mil" id="btn2" />
        </th>
        <th>
          <input type="button" value="LKR 5 Mil to 7.5 Mil" id="btn3" />
        </th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

<div>
  <table id="detailTable">
    <thead>
      <tr>
      <th>c1</th>
      <th>c2</th>
      <th>c3</th>
      </tr>
    </thead>
  </table>
</div>

JavaScript

var table;

$(document).ready(function () {
	$('#btn1').click(function(){
  	alert("hi");
    table = $('#detailTable').DataTable();
    table.destroy();
    table = getTables(1);
  });
  
  $('#btn2').click(function(){
  	alert("hi");
    table = $('#detailTable').DataTable();
    table.destroy();
    table = getTables(4);
  });
});

function getTables(n){
	var a = ["a","b","c", "d", "e", "f"];
  var arr = [];
  for (var i = n; i < 25; i++) {
    var item = {};
    item["c1"] = a[n] + Math.random();
    item["c2"] = a[n+1] + Math.random();
    item["c3"] = i;
    arr.push(item);
  };
  
  var dataSet = arr;
  console.log(dataSet);
  return $('#detailTable').DataTable({
    "bProcessing": true,
    "data": dataSet, // <-- your array of objects
    "columns": 
    	[
    		{"data": "c1"}, // <-- which values to use inside object
      	{"data": "c2"},
        {"data": "c3"}
    	]
  }); 
}