Reputation:
I've created a form that has a clone and remove button, if you click clone it clones the form, when i click remove it removes that form, so far so good.
Now for the tricky part, well i think it is...
When i click remove I want the div to remove but once there is only one remaining, I don't want that one to be able to be removed
Here's a jsfiddle of what i've got so far http://jsfiddle.net/vs8p5/5/
Here's the jquery
function updateClonedInput(index, element) {
$(element).appendTo("body").attr("id", "clonedInput" + index);
$(element).find(">:first-child").attr("id", "show_upload_image_link_" + index);
$(element).find(">:first-child").attr("name", "kandibox_theme_hero_options[show_upload_image_link_" + index + "]");
$(element).find(">:first-child").attr("value", "<?php echo $hero_options['show_upload_image_link_" + index + "']; ?>");
$(element).find(">:first-child").next().attr("id", "show_upload_image_link_button_" + index);
}
$(document).on("click", "button.clone", function(){
var cloneIndex = $(".clonedInput").length + 1;
var new_Input = $(this).parents(".clonedInput").clone();
updateClonedInput(cloneIndex, new_Input);
});
$(document).on("click", "button.remove", function(){
$(this).parents(".clonedInput").remove();
$(".clonedInput").each( function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement);
})
});
Upvotes: 2
Views: 96
Reputation: 36
Instead of just disabling the remove button the below hides the button when only one is remaining.
I added the following to the button.remove click event
if ($('.clonedInput').length < 2)
{
$('button.remove').hide();
}
and the following to button.clone click event
$('button.remove').show();
Update: http://jsfiddle.net/6eaQ2/10/
Added below to the css
.remove{ display: none; }
Upvotes: 1
Reputation: 22480
$(document).on("click", "button.remove", function(){
if($('.clonedInput').length > 1) {
$(this).parents(".clonedInput").remove();
$(".clonedInput").each( function (cloneIndex, clonedElement) {
updateClonedInput(cloneIndex + 1, clonedElement);
})
}
});
Upvotes: 1