Reputation: 282
Following is my piece of code which I am using to create dynamic forms by click "Add more..." button. My question is how can I add +1 on the dynamically generate fields so their names should look like testimonial1
, testimonial2
, testimonial3
and so on.
HTML:
<ul id="testimonial_ul" style="list-style-type: none; padding-left: 0px;">
<li>
<div class="field">
<input title="Testimonial" name="testimonial" class="testimonial required" type="text" placeholder="Testimonial"/>
<input name="testimonial_by" id="testimonial_by" class="testimonial_by required" type="text" placeholder="by..."/>
</div>
</li>
</ul>
<a href="#" id="more_testimonials">Add more...</a>
JS:
$("#more_testimonials").click(function() {
$("#testimonial_ul").append('<li><div class="field"><input class="testimonial" type="text" placeholder="Testimonial"/><input class="testimonial_by" type="text" placeholder="by..."/></div><a class="removeLI">Remove</a></li> ');
});
Upvotes: 0
Views: 205
Reputation: 3090
I have updated your fiddle CHECK HERE
var formInputLen = $('.testimonial').length;
Calculate the total elements with class testimonial
. And add the incremented counter to the id id="testimonial' + (formInputLen + 1) +'"
.
Upvotes: 1
Reputation: 1685
Try this:
var counter = 1;
$("#more_testimonials").click(function () {
$("#testimonial_ul").append('<li><div class="field"><input name="Testimonial'+counter+'" class="testimonial" type="text" placeholder="Testimonial"/><input name="Testimonial'+counter+'" class="testimonial_by" type="text" placeholder="by..."/></div><a class="removeLI">Remove</a></li> ');
counter++;
});
Working Fiddle.
Upvotes: 2
Reputation: 685
You can replace some special string to number of inputs. http://fiddle.jshell.net/k1twc1tz/1/
Upvotes: -1