Use jQuery add() to add element in a loop -
how use jquery's add()
add element in loop?
http://jsfiddle.net/smqtxtnt/2/
var allfields1 = $([]).add($('<input/>')).add($('<input/>').add($('<input/>'))); console.log(allfields1); var allfields2 = $([]); $([1,2,3]).each(function (index) { var input=$('<input/>').val(index); allfields2.add(input); }) console.log(allfields2);
i see why above code doesn't work described https://api.jquery.com/add/:
the following not save added elements, because .add() method creates new set , leaves original set in pdiv unchanged:
var pdiv = $( "p" ); pdiv.add( "div" ); // wrong, pdiv not change
...but don't know how it.
save result:
allfields2 = allfields2.add(input);
side note: don't need jquery object around numbers array if you're trying loop 3 times:
[1,2,3].foreach(function(value, index) { var input=$('<input/>').val(index); allfields2 = allfields2.add(input); });
or
$.each([1,2,3], function(index) { var input=$('<input/>').val(index); allfields2 = allfields2.add(input); });
Comments
Post a Comment