Add/Remove Input Fields Dynamically with jQuery

If you are looking to add and remove duplicate input fields, here’s another jQuery example below to do the task for you. This jQuery snippet adds duplicate input fields dynamically and stops when it reaches maximum.

If you read comment lines carefully, the process is pretty straight forward. We start with 1 input field and let user add more fields until the count reaches maximum. Same process goes to delete button, when clicked, it removes current text field by removing the parent element, which is div ele

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;
        
        $('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });
        
        $('#remScnt').live('click', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

HTML Code

Here’s HTML code you need to place within BODY tag of your page, perhaps within a FORM tag.

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
    <p>
        <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
    </p>
</div>

Demo

We start with single Input field and a “Add more Field” button to allow user to add more fields. The text input field is wrapped in div element, as explained above, on delete button click, it finds parent element, which is a div and removes it. 

Let's Think together, Say Something !