Dynamically Add and Remove HTML Elements using jQuery append(), after() and remove() Methods

Occasionally we might find a need to dynamically add and remove HTML elements like textbox into a web page or application. Yes occasionally, since it is very important that we have all the required information with us before starting to design the forms or pages. This however does not rule out the possibility of such requirement. There have been instances where users wanted to have convenient access to adding as well as removing elements on their web pages.

We can do this gracefully with a little help from jQuery methods. We are talking about methods like append(), after() and remove(), as these are the primary methods used for building a dynamic page with dynamically create elements. To be very honest, you don’t have to be a master of JavaScript to dynamically add or remove useful and interactive elements on your web page.

Must Read: Dynamically Add Textbox and Button using jQuery and Save Data in SQL Server using Asp.Net Web Method and Ajax

Dynamic-form-elements-using-jquery

Demo

These elements can also have attributes and properties, all assigned dynamically while creating and adding them on the web page. And after accomplishing their task, the controls can be removed from the page. In fact, a single form or page can be designed to reuse again and again for various purpose.

Related: How to Clone a Textbox Without its Value Using jQuery .clone() Method

The entire scenario can be understood with the help of a small program. We will create a container in the form of a DIV element, in which the dynamically created textboxes and button will be appended. So when the page loads, it will display 3 predefined “buttons”, whose primary function will be to add and remove the elements.

Along with the textboxes, we will also create and add a button to Submit the values in the textboxes. The Submit button will be created just once, and for the textboxes, we are setting a limit of 20 textbox per container.

The Markup
<html>
<head>
    <title>Create Elements Dynamically using jQuery</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js">
            </script>
    <style>
        body {
            font: 13px verdana;
            font-weight: normal;
        }
    </style>
</head>
<body>
    <div id="main">
        <input type="button" id="btAdd" value="Add Element" class="bt" />
        <input type="button" id="btRemove" value="Remove Element" class="bt" />
        <input type="button" id="btRemoveAll" value="Remove All" class="bt" /><br />
    </div>
</body>

Also Read: Quickly add a text Dynamically to a DIV element using jQuery

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

        var iCnt = 0;
        // CREATE A "DIV" ELEMENT AND DESIGN IT USING jQuery ".css()" CLASS.
        var container = $(document.createElement('div')).css({
            padding: '5px', margin: '20px', width: '170px', border: '1px dashed',
            borderTopColor: '#999', borderBottomColor: '#999',
            borderLeftColor: '#999', borderRightColor: '#999'
        });

        $('#btAdd').click(function() {
            if (iCnt <= 19) {

                iCnt = iCnt + 1;

                // ADD TEXTBOX.
                $(container).append('<input type=text class="input" id=tb' + iCnt + ' ' +
                            'value="Text Element ' + iCnt + '" />');

                // SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
                if (iCnt == 1) {

                    var divSubmit = $(document.createElement('div'));
                    $(divSubmit).append('<input type=button class="bt"' + 
                        'onclick="GetTextValue()"' + 
                            'id=btSubmit value=Submit />');

                }

                // ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
                $('#main').after(container, divSubmit);
            }
            // AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
            // (20 IS THE LIMIT WE HAVE SET)
            else {      
                $(container).append('<label>Reached the limit</label>'); 
                $('#btAdd').attr('class', 'bt-disable'); 
                $('#btAdd').attr('disabled', 'disabled');
            }
        });

        // REMOVE ONE ELEMENT PER CLICK.
        $('#btRemove').click(function() {
            if (iCnt != 0) { $('#tb' + iCnt).remove(); iCnt = iCnt - 1; }
        
            if (iCnt == 0) { 
                $(container)
                    .empty() 
                    .remove(); 

                $('#btSubmit').remove(); 
                $('#btAdd')
                    .removeAttr('disabled') 
                    .attr('class', 'bt');
            }
        });

        // REMOVE ALL THE ELEMENTS IN THE CONTAINER.
        $('#btRemoveAll').click(function() {
            $(container)
                .empty()
                .remove(); 

            $('#btSubmit').remove(); 
            iCnt = 0; 
            
            $('#btAdd')
                .removeAttr('disabled') 
                .attr('class', 'bt');
        });
    });

    // PICK THE VALUES FROM EACH TEXTBOX WHEN "SUBMIT" BUTTON IS CLICKED.
    var divValue, values = '';

    function GetTextValue() {

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

        $('.input').each(function() {
            divValue = $(document.createElement('div')).css({
                padding:'5px', width:'200px'
            });
            values += this.value + '<br />'
        });

        $(divValue).append('<p><b>Your selected values</b></p>' + values);
        $('body').append(divValue);
    }
</script>
</html>

Must Read: Dynamically Add Textbox and Button using jQuery and Save Data in SQL Server using Asp.Net Web Method and Ajax

An Overview of the Methods

Let us now find out what methods we have used in the program and what are uses.

jQuery append() Method

The append() method will add elements one after the other. A new element is added at the end of the last element. This method is attached with the dynamically created DIV elements, which serves as a container.

$(container).append()

$(divSubmit).append()

Also Read: Simple steps to Programmatically add LinkButton to a GridView Control – C# and Vb.Net

jQuery remove() Method

We used the remove() method for two particular reasons. The first purpose is to remove the controls one by one. The second time we used the method to remove all the elements attached to the container. Usually, the method remove() is used immediately after submitting the form or to reset a container or the entire page.

jQuery after() Method

The after() method helps in keeping the sequence proper while adding all the elements to the main container. We will add the submit button after all the textboxes have been added.

$('#main').after(container, divSubmit);

Also try… jQuery prepend() Method

This method will add an element at the beginning of the list of elements. So the newly added element will be at top of the list, followed by the elements added before. We are not using it in our demo, but you can do it yourself by making a slight change.

Modify this code…

$(container).append('<input type="text" id=tb' + iCnt + ' value=' + iCnt + ' />');

with this …

$(container).prepend('<input type="text" id=tb' + iCnt + ' value=' + iCnt + ' />');

Try this: Demo


Also Read: How to Create a Beautiful Dropdown Menu using Dynamic data extracted from an XML file using jQuery

Conclusion

Simple and yet useful, you can now add any number of elements on your web page dynamically using the above procedures and methods. However, if you want to add text to an existing DIV element using jQuery, then I would recommend that you check this article now.

Please don't forget to share this article with your friends and colleague on Twitter or Facebook. Thanks for reading.

Related Posts:

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!