html - Jquery, .length + 1 seems to be adding multiples of 7 -
i have jquery script add input fields @ click of button, need these numbering up, there 4 fields called first:
jsfiddle link http://jsfiddle.net/1orkxk2y/
ptno1 desc1 qty1 amnt1
when add field clicked expected ended numbers in brackets:
ptno2(7) desc2(7) qty2(7) amnt2(7)
code below:
$(document).ready(function() { $("#add").click(function() { var intid = $("#test div").length + 1; var fieldwrapper = $("<div id=\"test\" class=\"row\"/>"); var fptno = $("<div class=\"col-md-2\"><input type=\"text\" name=\"ptno" + intid + "\" class=\"form-control\" /></>"); var fdesc = $("<div class=\"col-md-2\"><input type=\"text\" name=\"desc" + intid + "\" class=\"form-control\" /></>"); var fqty = $("<div class=\"col-md-2\"><input type=\"text\" name=\"qty" + intid + "\" class=\"form-control\" /></>"); var famnt = $("<div class=\"col-md-2\"><input type=\"text\" name=\"amnt" + intid + "\" class=\"form-control\" /></>"); var removebutton = $("<div class=\"col-md-2\"><input type=\"button\" class=\"remove\" value=\"-\" /></>"); removebutton.click(function() { $(this).parent().remove(); }); fieldwrapper.append(fptno); fieldwrapper.append(fdesc); fieldwrapper.append(fqty); fieldwrapper.append(famnt); fieldwrapper.append(removebutton); $("#buildyourform").append(fieldwrapper); }); }); <fieldset id="buildyourform"> </fieldset> <input type="button" value="add charge" class="add" id="add" />
the expression $("#test div")
every div inside every #test. since add 5 div inside #test
each time, length
attribute increment 5. perhaps use global variable instead of reading dom each time?
var intid = 1; $(document).ready(function() { $("#add").click(function() { var fieldwrapper = $("<div id=\"test\" class=\"row\"/>"); var fptno = $("<div class=\"col-md-2\"><input type=\"text\" name=\"ptno" + intid + "\" class=\"form-control\" /></>"); ... intid++; }); });
edit: tim lewis pointing out multiple id
attributes produces invalid html.
Comments
Post a Comment