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 ?
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>
References:
Try this
<input type="button" class="adddiv" value="add" />
<div class="clean">
msg
</div>
<button class="close" value="close" > Remove </button>
$(".adddiv").on("click",function(){
if($('div.main1').length <= 5){
$('.clean').append('<div class="clean main1">msg<button class="close" value="close" /></div>');
}
else{
// do something else here
alert($('div.main1').length)
}
});
$(document).on("click",".close",function(){
$(this).closest('div').remove();
});
Check it out on JSfiddle
On every 'add' event - you can iterate on .clean div's using $.each() loop and count how many clean divs is added. Then if there's 5 already, you don't add any more div's. Check: https://api.jquery.com/each/
Example:
var counter = 0;
$('div.main1').each( function() {
counter++;
});
if(counter >= 5) {
// do nothing
}
else {
// add next div
$('.clean').after('<div class="clean main1">msg<button class="close" value="close" /></div>');
}
I prefer having the html-template in the dom instead of a string within the javascript code. This is the result.
I'd suggest not using a css className based on the amount of items, because one might delete number '2' out of 5 and add a new one, which would get another number '5'. Number '5' will then be duplicate.
$(function() { var $wrapper = $('#clean-wrapper'), $addButton = $wrapper.find('.adddiv'), $itemToClone = $wrapper.find('.itemToClone'); // Add new div. $addButton.on('click', function() { $itemToClone .clone() .appendTo($wrapper) .show(); $wrapper.trigger('mutation'); }); // Close div. $wrapper.on('click', '.close', function() { var $item = $(this).parents('.clean').first(); $item.remove(); $wrapper.trigger('mutation'); }); // Toggle button. $wrapper.on('mutation', function() { var itemCount = $(this).find('.clean:visible').length; $addButton.prop('disabled', itemCount >= 5); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="clean-wrapper"> <input type="button" class="adddiv" value="add" /> <div class="clean itemToClone" style="display: none;">msg <button class="close" value="close" /></div> </div>
Try below code:
HTML Code:
<input type="button" class="adddiv" value="add" />
<br/>
<div class="clean">
msg
<br/>
<input type="button" class="close" value="close" />
</div>
JS Code:
<script>
$(".adddiv").on("click",function(){
console.log($('div.clean').length);
if($('div.clean').length <= 4){
console.log("Test");
$('div.clean').last().after('<div class="clean">msg <br/><input type="button" class="close" value="close" /></div>');
}
else{
// do something else here
}
});
$(document).on("click",".close",function(){
if($('div.clean').length>1)
$(this).closest('div').remove();
});
</script>
Try following codes. Simplest solution:
<div id="main_container">
<div class="clean">
Message
<button class="close">CLOSE</button>
</div>
</div>
<script>
$("#adddiv").on("click",function(){
$('#main_container').append('<div class="clean">Message<button class="close">CLOSE</button></div>');
});
$(document).on("click",".close",function(){
$(this).closest('.clean').remove();
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.