Inkers
Inkers

Reputation: 219

Why is result displaying result plus previous result in loop?

I have an image and name displaying in a new div. However, I have run into a problem where the next time a person enters name and picture and presses save, their userDiv shows their name plus the previous users name. For example, there are two users: User 1 and User 2. When I select all users and loop through the results the names are logging differently. User one shows up as "User 1", but User 2 shows up as "User 1 User 2". From a quick look around I think it is because innerHTML gets all content from the parent div, but I'm not sure.

    var htmlStr="";
  var theID;
  var theName;
  var thePhoto;
  var len = results.rows.length;
  console.log(len);
    for(var i = 0; i < len; i++){
        theID = results.rows.item(i).id;
        console.log(theID);
        theName = results.rows.item(i).username;
            htmlStr += theName;
        console.log(theName);
        thePhoto = results.rows.item(i).imagepath;
        console.log(thePhoto);

        var imageHold= new Image();
        imageHold.src = thePhoto;
        console.log("this is the src:"+imageHold.src);
        var userDiv = document.createElement("div");//Create the div
        userDiv.innerHTML=htmlStr;
        userDiv.appendChild(imageHold);
        document.getElementById('showUsers').appendChild(userDiv);//append it to the document
        userDiv.style.display = 'block';

Upvotes: 0

Views: 67

Answers (1)

Manse
Manse

Reputation: 38147

Remove var htmlStr=""; and declare it within the loop on each iteration. So change

htmlStr += theName;

to

var htmlStr = theName;

and this should resolve your issue

Upvotes: 2

Related Questions