Thursday, July 9, 2015

Add Dynamically rows in HTML Table using jQuery


This article explains  how dynamically add Rows and Cells in an HTML Table using jQuery.


 <input type="button" id = "btnGenerate" value="Generate Table" />
<hr />
<div id="dvTable">


<script type="text/javascript" src=""></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, "ABC", "United States"]);
        customers.push([2, "XYZ", "India"]);
        customers.push([3, "PQR", "France"]);
        customers.push([4, "VEPSH", "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 />");

        //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 />");

        var dvTable = $("#dvTable");


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.


Post a Comment