user1221565
user1221565

Reputation:

Remove a cloned form but leave the last remaining form in place

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

Answers (2)

timat3d
timat3d

Reputation: 36

Instead of just disabling the remove button the below hides the button when only one is remaining.

http://jsfiddle.net/6eaQ2/

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

caramba
caramba

Reputation: 22480

http://jsfiddle.net/vs8p5/20/

$(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

Related Questions