In this article I will explain how to create a dynamic Table in HTML at runtime using jQuery. The columns, rows and cells will be dynamically created in the Table using jQuery.
Below is the HTML Markup of the page which consists of an HTML Button to create the dynamic HTML Table and an HTML DIV which will hold the dynamically created table.
<input type="button" id = "btnGenerate" value="Generate Table" />
<hr />
<div id="dvTable">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGenerate").click(function () {
//Build an array containing Customer records.
var customers = new Array();
customers.push(["Customer Id", "Name", "Country"]);
customers.push([1, "John Hammond", "United States"]);
customers.push([2, "Mudassar Khan", "India"]);
customers.push([3, "Suzanne Mathews", "France"]);
customers.push([4, "Robert Schidner", "Russia"]);
//Create a HTML Table element.
var table = $("<table />");
table[0].border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html(customers[0][i]);
row.append(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = $(table[0].insertRow(-1));
for (var j = 0; j < columnCount; j++) {
var cell = $("<td />");
cell.html(customers[i][j]);
row.append(cell);
}
}
var dvTable = $("#dvTable");
dvTable.html("");
dvTable.append(table);
});
});
</script>
Explanation:
Data Array
First an Array has to be created which will contain the Table Header and Cell values. Then a Table element is created using jQuery.
Adding the Header Row
The Header Row will be built using the first element of the Array as it contains the Header column text values.
First a row is inserted into the Table and then using the count of columns a loop is executed and one by one Table TH element is created and appended to the header row using jQuery.
Table insertRow Method: This method adds a new row to a Table at the specified index. If the index is supplied as -1 then the row will be added at the last position.
Adding the Data Rows
A loop is executed over the array elements and one by one a Row is created in the HTML Table. Then inside each Row a dynamic cell element is created and appended using jQuery.
Adding the dynamic Table to the Page
Finally the dynamically created table is added to the page by appending it the HTML DIV using jQuery
Note: You can also append an element to the body but then you won’t be able to set its placement on the page. Using a container such a DIV helps us add the dynamic element to the desired place.
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads