Input loses value when duplicated

I have a template for my form fields and I need these fields to be able to be duplicated multiple times.

See this as sample case:

<a href='#' id="add">Add</a><br /><br />
<div id="box">
    <div id="template">
        <input type="text" name="template"></input>
        <br /><br />
    </div>
</div>

The script:

var template = document.querySelector('#template');
var index = 1;

$('#template').remove();

$('body').on('click', '#add', function(e) {
    e.preventDefault();

    $('#box').append(template);

    var newInput = $('#box').html().replace(/template/g, 'input-'+index);

    $('#box').html(newInput);

    index++;
});

http://jsfiddle.net/bedex78/hkk7rx74/7/

Why is it whenever I input some value into the fields, the value disappears upon adding new one (ie. after clicking the ‘ADD’ button)?


Source: forms

Leave a Reply