Bunsen Honeydew
Bunsen Honeydew

Reputation: 71

For loop repeats each loop onto the next

I am trying to dynamically adjust the document.getElementById(divID) by using a loop. This seems to work...sorta

It keeps looping as you will see in the screenshot below.

let searchresult = function(response) {
    let output ="";
    for (let j = 0; j < response.length; j++) {
        let divID = response[j].resortcode + 'results';
        let container = document.getElementById(divID);

        output +=
            `
            <div class="${response[j].resortcode} ${response[j].roomcode}">
            </div>
            `;
        console.log(container);
        $(container).html(output);
    }
};

I have my container div set to the response[j].resortcode but I thought by using document.getElementById(divID) that it would only allow that resort code inside of a div with a corresponding resortcode Notice it is also looping the getElementByID more than once. enter image description here

I would like the output going to a premade div id in my html file (which it does, it just keeps repeating). Then loop the results <div class=${response[j].resortcode}"></div> into the corresponding premade div. Here is a photoshopped version of the desired result: enter image description here

EDIT: Adding console of original response. enter image description here

Any help is greatly appreciated.

Upvotes: 1

Views: 276

Answers (1)

Samathingamajig
Samathingamajig

Reputation: 13243

Your variable output is added upon every iteration and never reset, so when you set the html to output, it contains every previous iteration.

You can fix this by getting the innerHTML and adding onto instead of having an output variable.

You can also store the resortcode into a Set (a special kind of array that does not allow duplication of elements) and then console.log out those containers at the end.

let searchresult = function(response) {
    let resortCodes = new Set();
    for (let j = 0; j < response.length; j++) {
        resortCodes.add(response[j].resortcode); // add only happens if the resortcode isn't already in resortCodes
        let divID = response[j].resortcode + 'results';
        let container = document.getElementById(divID);

        container.innerHTML += `
            <div class="${response[j].resortcode}">
            <div class="roominfo"><p class="roomtitle"> ${response[j].roomname} - ${response[j].viewname}</p>
            </div>
            </div>
            `;
    }

    resortCodes.forEach(function (resortCode) {
        console.log(document.getElementById(resortCode + "results"));
    };
};

Upvotes: 2

Related Questions