Add and Remove Textbox Dynamically With jQuery | Code Snippet

21 Apr , 2013  Code Snippets,jQuery 

Add-Remove-Textboxes-Dynamically-jQueryCode Snippet #10: The code snippet can add and remove textbox dynamically with jQuery.

In a registration form, it is sometimes necessary to add a text box dynamically after filling out a previous text box or input field. This code snippet can actually add a textbox and even delete the added text box using jQuery’s .append() and .remove() functions.

In our sample, we will keep a text box initially static, with add and remove buttons. By clicking on the remove textbox button, the initial static texbox also can be removed. We can add up to 2 text boxes in our sample code. This can be changed to any other number according to your need. We also validate the number of text boxes added and removed.

Here is a sample demo before the explanation:


jQuery Code:


According the above HTML markup, we initially set up a textbox statically and assign id to the textbox. We have also added two buttons with ids “addButton” and “removeButton” to add and remove the textboxes respectively.

When the window loads, we set the document to the ready state. Create a counter with value 2. This value is for the number of textboxes. 2 indicates we can create maximum of 2 textboxes. When the #addButton is clicked, we check the counter if it is less than 2 then we add the new textbox HTML using the .append() function.

Similarly, when #removeButton is clicked, we reference the textbox with the right counter value and remove it using the .remove() function.

Hope you felt it easy to understand. If you have any clarifications, please let us know by comments. This tutorial can be kept as a reference to develop advanced forms for your projects.

, ,

  • pramod

    if we given a string name how we can remove.Instead of count like ‘str’

  • chichi

    Pls where on the page do we place the jquery code? The html is fine but I dont know how to save the jquery.. is it as a script in the head, if yes, wats the link.. pls explain

    • Please place in the jQuery code in your head with-in Your jQuery Code Here