Lee Fuller
Lee Fuller

Reputation: 2176

JQuery .clone() and .appendTo() causing multiple appends

So I've read numerous similar questions and answers - none seem to address this specific issue. So here goes.

Consider the following code:

<body>
<script>

    function addAttendee() {
        $('.newAttendee').clone().appendTo('.attendees');
    }

</script>

<form action="test2.php" name="testform" method="post">
    <span class="attendees">
    <input type="text" name="attendee[0][city]" value="city 1">
    <input type="text" name="attendee[0][state]" value="state 1">
    <input type="text" name="attendee[0][zip]" value="zip 1">
    </span>
<a href="#" name="addAttendee" onclick="addAttendee()">Add Attendee</a>
<br>
<input type="submit" onclick="getOutput()">
</form>

<div class="hideThis" style="display: none;">
    <span class="newAttendee">
        <br>
    <input type="text" name="attendee[1][city]" value="city 2">
    <input type="text" name="attendee[1][state]" value="state 2">
    <input type="text" name="attendee[1][zip]" value="zip 2">
    </span>
</div>

When I click "Add Attendee" the first time, I get what I want. But each subsequent click on that link causes double the previous inserted sections to be inserted. First click 1, second 2, third 4, etc.

Am I missing something?

Thanks to all in advance.

Upvotes: 1

Views: 448

Answers (2)

hr_117
hr_117

Reputation: 9627

This is because $('.newAttendee') select all elments with class newAttendee. And after you clone it you have 2 and so on. Changing the class after cloning would avoid this.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Because $('.newAttendee').clone() will clone all elements with that class

Try using first() or last() to only clone one of them

$('.newAttendee').first().clone().appendTo('.attendees');

Upvotes: 4

Related Questions