The following html snippet contains an input, a select and a link. When I click the link, I want to basically clone line, I want the new line to be appended to the last line. I also would like the link to be removed and be added to the last line. I want to have the even carried over as well. I will put my jquery code below the html.
<div id="lines">
<div class="line">
<span>Value</span><input type="text" name="value" class="value"/>
<span>Type</span>
<select name="type" class="type">
<option>$</option>
<option>%</option>
</select>
<a id="addLine" href="#">Add</a>
</div>
</div>
$(document).ready(function() {
$('#addLine').click(function() {
$('.line').clone({withDataAndEvents:true}).appendTo('#lines');
});
});
When I click add, it first adds a second line below the first one, but then when I click add again, it adds 2 lines, so I have 4, every time I click add, it is doubling the amount of lines which is what I don’t want. I also want add removed from all the lines except the last one. I probably will have a Remove as well to remove a specific line, so I would like suggestions on how to handle this.
That’s because you’re cloning the whole element set with the
lineclass, meaning the first time it adds one line, the second will add 2, the third will add 4. You can fix this by just cloning one line with.last: