Giraldi
Giraldi

Reputation: 17311

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)?

Upvotes: 1

Views: 442

Answers (2)

Remy Grandin
Remy Grandin

Reputation: 1686

It's because the inputed value isn't stored in the html itself.

A solution to your problem would be this :

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

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

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

    index++;
});

jsfiddle : http://jsfiddle.net/hkk7rx74/8/

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78545

You are replacing all of the HTML when using $('#box').html(newInput); - that includes all the inputs and values. Use a combination of clone to copy the template and append to add to the box without replacing its contents:

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

    var wrapper = $("<div>");
    wrapper.append($(template).clone());

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

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

    index++;
});

jsFiddle

Note: The reason I used clone here is so that you can modify the new box properly. You don't have to use html().replace, but can use DOM manipulation instead, e.g. wrapper.find("#template")

Upvotes: 4

Related Questions