0

I am looping through an array and appending the result to an HTML element on my page.

Here is my JavaScript/jQuery:

var numberOfFiles = email.file_id.length;
for (var fileIndex = 0; fileIndex < numberOfFiles; fileIndex++) {
  fileHTML += '<a href="downloadAttachment.php?file_id=' + email.file_id[fileIndex] + '" target="_blank">' + email.file_name[fileIndex] + '</a><br>';
  emailOpened.find('.file-attachment-wrapper').append(fileHTML);
}

The loop works and appends the content to my HTML, however, there is a small bug. The first item in my array is appended twice.

Here is what my array looks like before the loop:

["file1.png", "file2.pdf"]

After the loop is completed, the resulting HTML looks like this:

<a href="downloadAttachment.php?file_id=54d38004fdf902cb758b456a" target="_blank">file1.png</a><br>
<a href="downloadAttachment.php?file_id=54d38004fdf902cb758b456a" target="_blank">file1.png</a><br><a href="downloadAttachment.php?file_id=54d38004fdf902cb758b456b" target="_blank">file2.pdf</a><br>

As you can see, the file1.png is being added twice. Why is this happening?

3
  • Why are there values in the array before you even loop? That's probably why you're seeing file1 twice because it's in the array, then the loop is adding it again. Either start the count later or don't have anything in the array when you start. Commented Feb 5, 2015 at 16:30
  • whats the html look like before you run the JS? Commented Feb 5, 2015 at 16:31
  • it's the += combined with append, you're saying append file1, then append file1+file2, then later it'll be appened file1+file2+file3 which'll look like file1, file1+file2, file1 + file2 + file3. Just remove the += and make it = and you should be good to go. Commented Feb 5, 2015 at 16:31

2 Answers 2

5

Because you're using +=. This makes it append to the previous HTML. Replace it with a simple = and it will work.

Right now it's going like this:

(i=0)
file1

(i=1)
file1
file2

(i=3)
file1
file2
file3

And it ends up printing the earlier ones multiple times.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Can't believe I did not catch that :] Will accept your answer when SO lets me
1

Try changing fileHTML += by fileHTML =

edit:

You should put the append code outside the loop instead, it's more efficient.

var numberOfFiles = email.file_id.length;
var fileHTML = "";
for (var fileIndex = 0; fileIndex < numberOfFiles; fileIndex++) {
  fileHTML += '<a href="downloadAttachment.php?file_id=' + email.file_id[fileIndex] + '" target="_blank">' + email.file_name[fileIndex] + '</a><br>';
}
emailOpened.find('.file-attachment-wrapper').append(fileHTML);

Comments

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.