Lewis Smith Lewis Smith - 4 months ago 7
HTML Question

Jquery, .length + 1 seems to be adding multiples of 7

I have a jquery script to add some input fields at the click of a button, I need these to be numbering up, so there are 4 fields called first:

JSFIDDLE LINK http://jsfiddle.net/1orkxk2y/

ptno1
desc1
qty1
amnt1


when add field is clicked I expected this to be but I ended up with the 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 a charge" class="add" id="add" />

Answer

The expression $("#test div") will get every div inside every #test. Since you add 5 div inside #test each time, the length attribute will increment by 5 each times. Perhaps you could simply use a global variable instead of reading the 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++;
    });
});