Dynamically Adding And Removing TextBoxes On A Button Click Using jQuery

jQuery is a JavaScript library, which helps us in making our Webpages more interactive. If you are completely new to jQuery, I will recommend you to first go through the following blogs to get an overview of jQuery.

  1. jQuery Library
  2. jQuery Syntax
  3. jQuery Events

Adding UI elements dynamically is very easy with jQuery. We have jQuery append() method, which allows us to append the content at the end of the specified element and the remove() method, which helps us in removing the content from the specified element.

Let us understand append() and remove() better with the help of a simple example.

  1. <html>  
  2.   
  3. <head>  
  4.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
  5. </head>  
  6.   
  7. <body> <button id="Add">Click to add textbox</button> <button id="Remove">Click to remove textbox</button>  
  8.     <div id="textboxDiv"></div>  
  9.     <script>  
  10.         $(document).ready(function() {  
  11.             $("#Add").on("click"function() {  
  12.                 $("#textboxDiv").append("<div><br><input type='text'/><br></div>");  
  13.             });  
  14.             $("#Remove").on("click"function() {  
  15.                 $("#textboxDiv").children().last().remove();  
  16.             });  
  17.         });  
  18.     </script>  
  19. </body>  
  20.   
  21. </html>  
Output

Now, when you click on the "Click to add textbox", a textbox gets appended and when you "Click to remove textbox", the last added textbox is removed.



As you can see in the screenshot above, the highlighted area is our division with Id "textboxDiv". Initially, the div does not contain any element or textbox.

When the add button is clicked, we capture it with the help of Id selector and we have bound on click function. The function appends <div><br><input type='text'/><br></div> to the textboxDiv division with the help of append() method of jQuery. Similarly, we are using the remove method to remove the textbox.

Please refer to the image, given below for the explanation of remove() method, used in the example, shown above.

In this way, the elements can be easily added and removed in jQuery just on a button click or some other events too. The more you play with jQuery code, the more you learn. I hope this blog helped you.

You might also like.

Stay tuned. Keep learning.

Next Recommended Reading Open PopUp on Button Click Using JQUERY