2

How do I use jQuery's add() to add an element in a 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 my above code doesn't work as described by https://api.jquery.com/add/:

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $( "p" );
pdiv.add( "div" ); // WRONG, pdiv will not change

...but don't know how to do it.

0

1 Answer 1

3

Save the result:

allFields2 = allFields2.add(input);

Side note: You don't need a jQuery object around your numbers array if all you're trying to do is loop three 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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

The loop was just the first thing to come to mind to demonstrate. Your original answer did the trick. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.