1

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.

Lee Fuller
  • 2,116
  • 3
  • 19
  • 27

2 Answers2

4

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');
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • You could better use $('.newAttendee').clone()..removeClass('newAttendee').appendTo('.attendees'); – Siderite Zackwehdex Mar 19 '16 at 16:03
  • @SideriteZackwehdex but that might have an impact on css or other code . It's very simple to only clone one of them – charlietfl Mar 19 '16 at 16:04
  • 2
    I think the intention of the code was not to add spans with the newAttendee class, but only use the one as a template. If not, then you are right. – Siderite Zackwehdex Mar 19 '16 at 16:06
  • @SideriteZackwehdex either way cloning only one will work. Can also store a clone when page loads. – charlietfl Mar 19 '16 at 16:09
  • @charlietfl Bingo. That did it. Makes sense. I was under the (false) impression that clone only copied the existing section one time. I see now where I was wrong. Thanks everyone. – Lee Fuller Mar 19 '16 at 16:25
0

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.

hr_117
  • 9,589
  • 1
  • 18
  • 23