I’m new to jquery and I’m 100% sure I’m making a logical error but I can’t see it. Basically as a user types a item in a field I want to clone the fields so they can continue adding more info. In the example I’m working on, I’m trying to create a list of siblings and their age.
Here’s my code:
$(document).ready(function () {
$("input[name='age']").on('keydown', function() {
//is it the last input?
if (this == $("input[name='age']:last", this.form)[0]) {
//insert an empty clone of the current input
//$(this).after($(this).clone(true).val(''));
$('.family').clone().insertAfter(".family");
}
Here’s the html:
<form>
<div class="family">
<input name="age" value=0> <input name="sibling" value="name?">
<hr />
</div>
</form>
If I use $(this).after($(this).clone(true).val('')); then it works but it only clones one field(the age one) so I tried to replace it with $('.family').clone().insertAfter(".family"); to clone the div class but it clones the fields only once. If I start typing my first siblings info then the second form will appear but if I start typing on the second form then nothing new appears after that.
Its just a guess but I think the if statement is not matching so the clone isn’t being created(I’m new so this idea could be wrong). If this is the case then I’m confused because I’m cloning the same names of the input fields so input[name='age']:last should match the last age field..not sure.
Any idea what I’m doing wrong?
You’re going to have to make your
keydownevent handler take note of future elements as well (i.e. the new<div>elements you’re cloning and inserting).Change
to
i.e. (with some corrections / optimizations as well)