Add Rows to a Table Dynamically using jQuery

← PrevNext →

HTML tables allow developers to show data in rows and columns. Yes, we know this. We also know how quickly we can add rows and columns to a table to show text, images and links. Although, developers often no-a-days use a lightweight alternative, such as the DIV, a table is still a very useful element. In this post, I’ll show you a simple example on how you can add rows to an HTML table dynamically using jQuery.

Dynamically add rows to table using jQuery

See this demo

This example is useful when you don’t have a full list of data with you at the design time. You extract data dynamically from a remote source, such as, a database and then wish to add and show the data in tabular format on the web page.

jQuery provides some very useful methods designed specifically for these situations. Yes, I am talking about methods such as the jQuery .append(), .each() and .after(). I have explained about these methods before in my previous articles. Here in this article too, I am using these two methods in my example.

Related: Loop through Elements, Arrays and Objects using jQuery .each() Function

Finally, I’ll show you how you can design a form using dynamically created <table> with <tr> and <td> tags, and add input boxes to each row along with few buttons (submit and reset).

Therefore, first let’s see how we can add rows (that is <tr> and <td> tags) to a table with jQuery. All I have in the <body> is the <table> tag.

The Markup
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
    <table></table>
</body>
The jQuery Script
<script>
    $(document).ready(function () {

        $('table').append('<tr><td> Name </td><td> Profession </td></tr>');

        // ADD ROWS TO THE TABLE.
        $('table tr:last')
            .after('<tr><td>Arun Banik</td><td>Blogger</td></tr>');
    });
</script>

I have only added a <table> tag in the markup section, with no rows at all. Using jQuery .append() method, I have added the first row (also serves as a header) to the table. Later, I have used jQuery .after() to add another row to the table.

The .after() method will have no effect unless and until the <table> has at least one row in it. In-addition, I am using jQuery :last selector, which will look for the last row (<tr>) in the table. This will ensure that the .after() adds a new row after the last row (not in the middle).

Also Read: Dynamically Add Textbox and Button using jQuery and Save data to a Database table

A Working Example

Now, let’s design a simple form using the above procedure and methods. Dynamically I wish to add input boxes (inside <td>) in each newly added row, also add two buttons, one to submit the form data and another to reset the form (clear all the input boxes).

The Markup and the Script
<!DOCTYPE html>
<html>
<head>
    <title>Dynamically Add Table Row using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        table 
        {
            width: 100%;
            font: 17px Calibri;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        .input, div {
            font:13px Verdana;
        }
    </style>
</head>

<body>
    <p>Click the button to add rows to the table!</p>
    <p><input type="button" id="bt" value="Click to add rows!" /></p>

    <!--// ADD JUST THE TABLE TAG. WE'LL CREATE AND ADD ROWS TO THE TABLE DYNAMICALLY.-->
    <table></table>
</body>

<script>
    $(document).ready(function () {

        $('#bt').click(function () {

            // IF THERE IS NO <tbody> INSIDE THE <table> TAG.
            $('table').append('<tr><td> Name </td><td> Designation </td></tr>');

            // ADD MORE ROWS.
            // USING AN ARRAY ADD 5 ROWS.
            $.each(new Array(5), function (i) {
                $('table tr:last')
                    .after('<tr><td><input id="name' + (i + 1) + '" type="text" class="input" /></td>' +
                        '<td><input id="desig' + (i + 1) + '" type="text" class="input" /></td>' +
                        '</tr>');
            });

            // ADD TWO BUTTONS (SUBMIT AND RESET) AT THE END OF THE TABLE.
            $('table tr:last')
                .after('<tr><td><input type="button" id="btSubmit" value="Submit"></td>' +
                    '<td><input type="button" id="btReset" value="Reset"></td>' +
                    '</tr>');


            // EXTRACT THE VALUES ENTERED IN THE DYNAMICALLY CREATED 
            // INPUT BOXES.

            var values, divResult;

            $('#btSubmit').click(function () {

                $(divResult)
                    .empty()
                    .remove();
                values = '';

                $('.input').each(function (i) {
                    divResult = $(document.createElement('div'))
                    .css({
                        padding: '5px', width: 'auto'
                    });

                    if (typeof $('#name' + (i + 1)).val() != 'undefined' &&
                        $('#name' + (i + 1)).val() != '') {

                        values += '<b>Name</b>: ' + $('#name' + (i + 1)).val() +
                            ', <b>Designation</b>: ' + $('#desig' + (i + 1)).val() + '<br />'
                    }
                });

                // SHOW THE EXTRACTED VALUES ON THE FORM.
                $(divResult).append('<p><h3>Employee Details</h3></p>' + values);
                $('body').append(divResult);
            });

            // RESET (CLEAR) ALL THE "TEXT" FIELDS.
            $('#btReset').click(function () {
                $(':input')
                .not(':button')         // NOT THE BUTTONS.
                .val('');
            });

        });

        
    });
</script>
</html>
Try it

In the above script, I have added few more jQuery methods, such as, .each(), .after(), .empty(), .remove() etc. to design a simple and yet a functional form.

The .each() method will loop though the <table>, creating and adding five rows to the already appended first row with two columns (as header). I am using an Array for the loop to execute 5 times.

$.each(new Array(5), function (i) {
    ...
});

Each row has an Input box with a unique id and I have also defined a class each to the input elements. Next, outside the loop I have added another row with two input elements of type button. In addition, there are two click events, one to submit the contents of each input boxes and to reset the form.

$('#btSubmit').click(function () {
    …
});
$('#btReset').click(function () {
   …
});
See this demo

That’s it. Let me know if you have implemented the above example in your application. If you have any suggestions or queries, simply leave a message below.

Thanks for reading .

← PreviousNext →