Dynamically Create And Remove Textboxes Using jQuery

In this example, you will learn how to dynamically create and remove textboxes using jQuery. You can see the code given below along with a demo to understand what happens inside of the HTML and jQuery to create a dynamic textbox and remove button over here. jQuery has made our life simple and gives you pretty procedures to handle the HTML and CSS. In this example, you can see a button which is used to create dynamic textboxes and also one more button is given to show the values of dynamically created textboxes.
 
The program is pretty simple to understand and execute. The following jQuery code lets you get the approach to create a dynamic textbox and button.
 
jQuery code to handle dynamic textbox creation,
  1. <script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  2. <script type="text/javascript">  
  3. $(function () {  
  4.     $("#buttonAdd").bind("click"function () {  
  5.         var div = $("<div />");  
  6.         div.html(GenerateTextbox(""));  
  7.         $("#TextBoxContainer").append(div);  
  8.     });  
  9.     $("#buttonGet").bind("click"function () {  
  10.         var values = "";  
  11.         $("input[name=CreateTextbox]").each(function () {  
  12.             values += $(this).val() + "\n";  
  13.         });  
  14.         alert(values);  
  15.     });  
  16.     $("body").on("click"".remove"function () {  
  17.         $(this).closest("div").remove();  
  18.     });  
  19. });  
  20. function GenerateTextbox(value) {  
  21.     return '<input name = "CreateTextbox" type="text" value = "' + value + '" /> ' +  
  22.             '<input type="button" value="Remove" class="remove" />'  
  23. }  
  24. </script> 
 HTML code lets you add and show buttons.
  1. <input id="buttonAdd" type="button" value="Click here to Add Textbox" />  
  2.   
  3. <div id="TextBoxContainer">  
  4.     <!--Textboxes will be added here -->  
  5. </div>  
  6.   
  7. <input id="buttonGet" type="button" value="Show Values" /> 

Explanation

In the given example, when we click “buttonAdd” button, it will fire a click event using jQuery. The event will cause it to generate a div and finally will call a function named GenerateTextbox(). The function is going to return textbox and remove button respectively. Whenever you click “buttonAdd”, you will see a textbox and a button nested with a <div> tag.

Finally, this example lets you know how to dynamically create and remove textboxes using jQuery. Subscribe to us to get daily updates.