Search code examples
javascriptjqueryclone

Cloning element only once and removing it


I have set up the following JSFiddle to demonstrate what I am doing. As you can see, I have various inputs. Each input has a checkbox to add an additional row. If a checkbox is checked, it should add a new input underneath the checked input.

Now what I have seems to do that without any problems - although it could probably be improved.

At the moment I am having issues with

$(this).closest(".labelAndInput").remove();

So each section (I have given them different background colours to show the sections) should only be allowed to have one additional input. At the moment, if I check the box, uncheck it, then check it again, it adds a third input.

The above problem can probably be solved with the following. If a checkbox is unchecked, it should remove the cloned div. This is where I am having issues at the moment. How can I remove the clone if the checkbox is unchecked? It should remove the div it is related too, and not a random clone.

Any information appreciated.

Thanks


Solution

  • Simply give your clone a class to identify it exactly. jsfiddle

     $(function() {
       $('input:checkbox[name="labelNewline"]').change(function() {
         if ( $(this).is(':checked') ){
            var clone = $(this).parent().siblings(".labelAndInput").first().clone().insertAfter($(this).parent());
            clone.addClass('clone');
         } else {
             $(this).parent().siblings(".clone").remove();
         }
       });
     });