How to add and remove div dynamically in jQuery

In this tutorial I will explain you how to add and remove div dynamically in jQuery. The entire scenario can be understood with the help of a small program. We will create a container in the form of a DIV element. We will put two text box inside the DIV and two button ousite the div to add and remove the div using jQuery. Now create a folder name Test in your localhost and create index.php file inside the folder. You need to add jQuery CDN on the top of the you file to load jQuery.

Below are the code. Include the code inside the index.php file

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    alert("hello");
       var counter = 2;
       $("#addbutton").click(function(){
           
                     var newTextBoxDiv = $(document.createElement('div')).attr("id",'TextBoxDiv' + counter);
                     newTextBoxDiv.after().html('<label>Deal </label> '+counter+'<br><input type="text" id="textbox'+counter+'" name="v_deals[]"  class ="form-control" value=""><br><label>Location</label><br> <input type="text" id="textbox'+counter+'" name="v_location[]"  class ="form-control" value="">');
                     newTextBoxDiv.appendTo("#TextBoxesGroup");
                     counter++;
              });
       $("#removeButton").click(function () {
                      if(counter==1){
                      alert("No more textbox to remove");
                      return false;
             }  
              counter--; 
              $("#TextBoxDiv" + counter).remove();
 
    });
});

 
</script>
</head>
</body>
       <div id='TextBoxesGroup'>
 
       <label>Deal 1</label><br>
 
       <input type="text" id="textbox" name="v_deals[]"  class ="form-control" value=""><br>
 
       <label>Location</label><br>
 
       <input type="text" id="textbox" name="v_location[]"  class ="form-control" value="">
 
       </div><br><input type="button" class = "btn btn-primary" id="addbutton" value="Add DIV"><br>
       <input type="button" class = "btn btn-primary" id="removeButton" value="Remove DIV"><br><br>
 
 </body>
 </html>



Now run copy and paste the following URL in your browser. http://localhost/Test

You can add and remove the DIV dynamically.

Hope this small articale will help you to understand how to add and remove div dynamically in jQuery.

  • Paul Bowden

    Morning – I get Syntax Error on Line 43

    • Ricky Negi

      I have updated the code again check and let me know

  • Paul Bowden

    newTextBoxDiv.after().html(‘Deal ‘+counter+’

  • Paul Bowden

    YAY that’s better – one thing, the first time you click Add Div it says Deal 1 the same as the original?