Thursday, July 9, 2015

Add Dynamically rows in HTML Table using jQuery

Introduction

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

HTML

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

Script 

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

0 comments:

Post a Comment