bert
bert

Reputation: 4059

Append a copy of an element containing an input

So here is my JS:

$('.options_button').click(function() {
    $( ".new_input" ).last().clone().appendTo( ".options" );
});

and here is my HTML:

              <div class="options">
                <h2>Options</h2>
                <span class="input input--kuro">
                    <input id="inputID" class="input__field input__field--kuro" type="text" id="input-7" placeholder="..." />
                    <label class="input__label input__label--kuro" for="input-7"></label>
                </span>
                <span class="input input--kuro">
                    <input id="inputID" class="input__field input__field--kuro" type="text" id="input-8" placeholder="..."/>
                    <label class="input__label input__label--kuro" for="input-8"></label>
                </span>
                <span class="input input--kuro new_input">
                    <input id="inputID" class="input__field input__field--kuro" type="text" id="input-9" placeholder="..."/>
                    <label class="input__label input__label--kuro" for="input-9"></label>
                </span>
            </div>
            <button class="options_button">
                <i class="fa fa-plus"></i>
                <p>Option</p>
            </button>

Clicking my button clones one of the spans that contains an input (and label) and appends it below the others. I thought I was being clever, but the problem is that it doesn't just clone the blank input field, but when the input is filled it also clones what has been entered too. So clearly cloning the input is not the way forward.

Can anyone give me an idea of how I can modify what I have done? I know it's possible to just add new inputs using jQuery, but I don't just want to do that, I want to add blank copies of the span and the label and input that it contains.

Upvotes: 1

Views: 63

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this

$('.options_button').click(function() {
    $( ".new_input" ).last().clone().appendTo( ".options" ).find('input').val('');
});

Example

Upvotes: 1

Related Questions