Reputation: 4270
I want to append a div(chunk of code ) onclick of a link up to 2 times only. After appending second time, I want to hide the link "add more provider".
My present code : Demo
$('#addProviderLink').click(function(e) {
var addProviderDiv = $('<div class="formData"><strong><label>Additional Provider</label></strong><input type="text" class="ac_input width226" value="" /><span class="f11"><a href="#" class="underline removeThis">Delete</a></span> </div>');
$('.addProContainer').append(addProviderDiv);
});
$('.removeThis').live('click', function(){
$(this).parent().parent().remove();
});
Upvotes: 0
Views: 310
Reputation: 5921
Add this to your click()
handler:
if ($(".addProContainer .formData").length > 1) {
$(this).hide()
}
And then add this to your live()
handler:
if ($(".addProContainer .formData").length < 2) {
$('#addProviderLink').show()
}
Side Note: live()
is deprecated. You should do this instead:
$(".addProContainer").on("click", ".removeThis", function() {
...
});
Here be the fiddle: http://jsfiddle.net/gwcoffey/U52ZG/1/
Upvotes: 0
Reputation: 82231
Add the condition to check the length of appended dom:
if($('.addProContainer .underline').length<2)
$('.addProContainer').append(addProviderDiv);
This will even work after removing the elements.
Upvotes: 2
Reputation: 25527
USe a counter for it
var count = 0;
$('#addProviderLink').click(function (e) {
count++;
if (count == 2) {
$("#addProviderLink").hide();
}
var addProviderDiv = $('<div class="formData"><strong><label>Additional Provider</label></strong><input type="text" class="ac_input width226" value="" /><span class="f11"><a href="#" class="underline removeThis">Delete</a></span> </div>');
$('.addProContainer').append(addProviderDiv);
});
Edit
$('.removeThis').live('click', function(){
count--;
$(this).parent().parent().remove();
$("#addProviderLink").show();
});
Upvotes: 4