Dynamically add and remove element with jQuery

In this post, I show how you can add and remove new elements within your web page with jQuery.

There are two approaches to doing this –

  • Pre-made all elements
  • Dynamically create a new element

The first case is easy but you have to create all of the elements at once and hide them which is not required currently.

When you have to add an element you need to display the element one by one and for removing hide them.

Here the problem is – there are multiple unused elements are available which occupy space within your code and make it messy even if you don’t have needed some of the elements.

The second solution is better than the first where you can create and remove an element dynamically when you have to require.

In this tutorial, I am using the second solution.

Dynamically add and remove element with jQuery


Contents

  1. HTML
  2. jQuery
  3. Demo
  4. Conclusion

1. HTML

Created a <div class='element' id='div_1'> which have one textbox and a <span class='add'>.

Completed Code

<div class="container" >
 <div class='element' id='div_1'>
  <input type='text' placeholder='Enter your skill' id='txt_1' >&nbsp;<span class='add'>Add Skill</span>
 </div>
</div>

2. jQuery

Add Element

When the add class gets clicked –

Calculating the total number of elements being added if it does not reach its maximum e.g. 5 then add new <div> element with a textbox and a <span class='remove' > otherwise not adding any more.

Here, I set the maximum value to 5 you can change it by editing the following code –

var max = 5;

Remove Element

When the remove class gets clicked –

Using clicked <span> element id to remove the <div> container.

Completed Code

$(document).ready(function(){

 // Add new element
 $(".add").click(function(){

  // Finding total number of elements added
  var total_element = $(".element").length;
 
  // last <div> with element class id
  var lastid = $(".element:last").attr("id");
  var split_id = lastid.split("_");
  var nextindex = Number(split_id[1]) + 1;

  var max = 5;
  // Check total number elements
  if(total_element < max ){
   // Adding new div container after last occurance of element class
   $(".element:last").after("<div class='element' id='div_"+ nextindex +"'></div>");
 
   // Adding element to <div>
   $("#div_" + nextindex).append("<input type='text' placeholder='Enter your skill' id='txt_"+ nextindex +"'>&nbsp;<span id='remove_" + nextindex + "' class='remove'>X</span>");
 
  }
 
 });

 // Remove element
 $('.container').on('click','.remove',function(){
 
  var id = this.id;
  var split_id = id.split("_");
  var deleteindex = split_id[1];

  // Remove <div> with id
  $("#div_" + deleteindex).remove();

 }); 
});

3. Demo

View Demo


4. Conclusion

Within the demonstration, I have used input fields you can do the same process with any other element like Select, Radio button, Checkbox, etc.

If you found this tutorial helpful then don't forget to share.

14 thoughts on “Dynamically add and remove element with jQuery”

  1. Hi Yogesh,
    Im looking for a solution for my code, maybe you can help me.

    I understand that to remove dynamically added element i should use an Event Delegation, the problem is when a customer click on remove button i first send a request with ajax to remove this element from DB and then when it success i want to remove it from dom, what means i dont have click event

    function ajaxSend(data, func){
    $.ajax({
    url: url( client_url() + ‘/report/forums/ajax/ajaxMethod’ ),
    type: ‘GET’,
    dataType: ‘html’,
    data: data,
    success: function(results){
    $(‘#card’ + data[‘id’] + ” ).remove();
    }
    });
    }

    remove is not working for me.
    Any suggestion?

    Reply
  2. Great tutorial… Easy to understand & learn.
    Can you share How to insert multiple data in PHP using add remove input field in jquery

    Reply
    • Hi Rapsan,
      If you want to input many variables, all called name ($_POST[‘name’]) you can sit back and let php do the work for you! If you leave the array as unset, it will automatically set it. So if we have in our code:
      1:
      2:
      we only get the last one collected.
      If we set it to:
      1:
      2:
      the open and close square brackets mark it as an array. Once we get to php, we can do many things, but we can work as simply as:
      $name=$_POST[‘name’];
      $a=count($name);
      $i=0
      while ($i<$a)
      {
      # do what you want with the data
      echo '’.$name[$i].”;
      $i++;
      }

      Reply
  3. Nice one and I hope you can help here. I am cannot find on internet a tutorial to dynamically add/remove a form with different input types. The idea is to build a form for “products attributes”. Something exactly like you can see here:
    http://demo.activeitzone.com/shop/admin/product
    Please login as an admin and go to Products -> Physical Products -> All Products -> Create Product -> Customer Choice Options tab.

    Could you make a tutorial for that kind of form builder? You would be the best if you can help with that!

    Reply

Leave a Comment