Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
Nested loop only rendering last indexed item using jquery appendPe

Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.

function displayDrinkData(drinkName) {

var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName

$.ajax({
    url: queryURL,
    method: "GET"
}).then(function (response) {
    console.log(response);

    var results = response.drinks;

    for (var i = 0; i < results.length; i++) {

        console.log(results[i]);

        var eachDrink = results[i];

        var drinkDiv = $("<div>");

        var drinkName = results[i].strDrink;

        for (var k = 1; k < 16; k++) {

            console.log(eachDrink['strIngredient' + k]);

            var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])              

        }

        var pOne = $("<p>").text("Drink name: " + drinkName);

        var drinkInstructions = results[i].strInstructions;

        var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
        var drinkImage = $("<img>");

        drinkImage.attr("src", results[i].strDrinkThumb);

        drinkDiv.append(pOne);
        drinkDiv.append(ingList);
        drinkDiv.append(pTwo);
        drinkDiv.append(drinkImage);

        $("#drinks-view").append(drinkDiv);
    }

})

} enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Because var ingList is inside loop, not appending, but creating a new one every time.

var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
    console.log(eachDrink['strIngredient' + k]);
    ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));              
}

Declare variable outside loop, and append <li> for each element.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!