How to add/remove textbox dynamically with jQuery

How-to-add-emove-textbox-dynamically-with-jQuery

How to dynamically add and remove text boxes using jQuery. You can see the code given below along with a demo to understand what happens inside of the HTML and jQuery to add a dynamic textbox and remove button over here.

HTML Code

<html>
<head>
<title>jQuery add / remove textbox example</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
<style type="text/css">
div{
	padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
</head><body>
<div id='TextBoxesGroup'>
	<div id="TextBoxDiv1">
		<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
	</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>

jQuery Code

<script type="text/javascript"> 
$(document).ready(function(){ 
    var counter = 2; 
    $("#addButton").click(function () { 
   if(counter>10){ 
            alert("Only 10 textboxes allow"); 
            return false; 
   }    
 
 var newTextBoxDiv = $(document.createElement('div')) 
      .attr("id", 'TextBoxDiv' + counter);         
 newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' + 
       '<input type="text" name="textbox' + counter +  
       '" id="textbox' + counter + '" value="" >'); 
             newTextBoxDiv.appendTo("#TextBoxesGroup"); 
 counter++; 
     }); 
 
     $("#removeButton").click(function () { 
 if(counter==1){ 
          alert("No more textbox to remove"); 
          return false; 
       }    
 counter--; 
        $("#TextBoxDiv" + counter).remove(); 
 
     }); 
 
     $("#getButtonValue").click(function () { 
 
 var msg = ''; 
 for(i=1; i<counter; i++){ 
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); 
 } 
       alert(msg); 
     }); 
  }); 
</script>

Output this code

Learn Tutorials Point
We Well organized and easy-to-understand Interactive tutorials With lots of examples of how to use Tutorials WordPress, PHP, Bootstrap, Bootstrap 4, HTML, CSS, AJAX, jQuery, Woocommerce, Post, Database, Javascript, Theme, Responsive, Templates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact us

Fill in the form below or give us a call and we'll contact you. We endeavour to answer all enquiries within 24 hours on business days.