Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda