Dan Dan - 1 month ago 14
Javascript Question

Insert and delete multiple div using jQuery

Hi I know how to add div dynamically when button click, and how to delete that div using jQuery:

<input type="button" class="adddiv" value="add" />
<div class="clean">
msg
<button class="close" value="close" >
</div>

<script>
$(".adddiv").on("click",function(){
$('.clean').after('<div class="clean main1">msg<button class="close" value="close" /></div>');
});

$(document).on("click",".close",function(){
$(this).closest('div').remove();
});

</script>


But here I need to make restrict maximum number of clean div in the page is 5 . If user add more than 5 div i need to restrict .

How to do this ?

Answer

I'd suggest the following, though note that I chose to add the 'indexing' to a custom data-* attribute, in this case data-index, since it avoids the necessity of parsing the element's class-names to retrieve that index; the data-index values can be retrieved either with plain JavaScript:

var index = HTMLElement.dataset.index;

Or through jQuery:

var index = $(element).data('index');

That said, my proposed solution:

// using the on() method to bind the anonymous function
// of that method as the event-handler for the 'click'
// event fired on the '.adddiv' element:
$('.adddiv').on('click', function() {

  // caching the current '.clean' elements present on
  // the page:
  var cleans = $('.clean'),

  // cloning the first of those elements, including
  // descendants, data and event-handlers, using
  // clone(true, true):
    newClean = $('.clean').eq(0).clone(true, true),

  // retrieving the number of '.clean' elements
  // currently in the document:
    num = cleans.length;

  // setting the 'adddiv' <input> element to be
  // disabled if after the next addition (which
  // is completed within this function) there
  // will be more than 6 '.clean' elements in
  // the document:
  this.disabled = num + 1 >= 6;

  // if the current number of '.clean' elements
  // is less than 6:
  if (num < 6) {

    newClean
      // adding the value of the 'data-index' attribute,
      // JavaScript is zero-indexed so the new index is
      // equal to the current number of 'clean' elements:
      .attr('data-index', num)

      // and then we insert the cloned element after the
      // last of the current '.clean' elements present
      // in the document:
      .insertAfter(cleans.eq(num - 1));
  }
});

// using on() again to bind clicks on the elements
// matched by the supplied selector, delegating the
// event-listening to the document (although the
// closest ancestor element present in the page
// would be a better choice):
$(document).on('click', '.clean > .close', function() {

  // removing the closest ancestor <div> element of
  // the clicked button:
  $(this).closest('div').remove();

  // caching the '.clean' elements in the document
  // after removing the unwanted element:
  var clean = $('.clean');

  // iterating over each of the (remaining) '.clean'
  // elements and updating the 'data-index' property
  // to be equal to the index of insertion:
  clean.attr('data-index', function(i) {

    // it seems likely that the first of the elements
    // should have no index (from what I can see in
    // the question, therefore if i (the index of
    // the current element in the collection) is equal
    // to zero we return an empty string, otherwise we
    // return the index:
    return i === 0 ? '' : i;
  });

  // updating the disabled property of the '.adddiv'
  // <input> element, to reenable if the current
  // number of 'clean' <div> elements is less than 6
  // (though because we enable an element by updating
  // its disabled property it does look a little
  // confusing and 'backwards' almost):
  $('.adddiv').prop('disabled', $('.clean').length >= 6);
});

$('.adddiv').on('click', function() {
  var cleans = $('.clean'),
    newClean = $('.clean').eq(0).clone(true, true),
    num = cleans.length;
  this.disabled = num + 1 >= 6;

  if (num < 6) {
    newClean.attr('data-index', num).insertAfter(cleans.eq(num - 1));
  }
});

$(document).on('click', '.clean > .close', function() {
  $(this).closest('div').remove();

  var clean = $('.clean');
  clean.attr('data-index', function(i) {
    return i === 0 ? '' : i;
  });

  $('.adddiv').prop('disabled', clean.length >= 6);
});
/* hiding the close button if there is
   only one <div> present within the
   common parent */
div:only-of-type button.close {
  display: none;
}

[data-index]::after {
  content: attr(data-index);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="adddiv" value="add" />
<div class="clean">
  msg
  <button class="close">Close</button>
</div>

JS Fiddle demo.

References: