Question

I am trying to use the jQuery clone method to duplicate an input element as many times as needed. The input element is nested within a fieldset tag and other div tags. The problem is that the cloned group of elements come out in a different order. More importantly the INPUT element is no longer nested where it was and this breaks the UI.

e.g. Original structure (simplified)

<fieldset><div><input /></div></fieldset>

The cloned outcome:

<fieldset><div></div></fieldset><input />

Here is a JSfiddle link showing the issue in action: jsfiddle

Was it helpful?

Solution

The issue is stemming from the fact you are using incremental id attributes, and are trying to calculate the next in the sequence on the fly. This is always problematic, and is rarely the best solution.

Use class attributes to group similar elements - it's what they were designed for. Your code becomes much simpler too.

<div id="insert-placeholder"></div>
<fieldset class="template-image-upload-wrapper">
    <legend>Image upload</legend>
    <div class="form-group">
        <div class="col-md-12">
            <input class='template_image_upload' class='form-control input-md' title='Upload an image.' name='editPage' type='file' value='' /> 
            <span class="help-block"></span>    
        </div>
    </div>
</fieldset>
$(".template-image-upload-wrapper").clone(false).insertBefore("#insert-placeholder");

Updated fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top