Problem adding div tags from javascript

0

Well, I searched and looked at my code trying to find the error but I do not realize what it is.

I explain a little, I bring orders from my bd, I use the api of Google Maps waypoints where I pass an array with the directions of the orders so that I can return the order according to the best route, so I can show them in a listed in that order.

This is my js, where I assemble the div with the data of the order

function armarListado(){
    var div = document.getElementById("listado");
    var i = 0;

    console.log("Orden: " + orden.length + ", Waypoints: " + waypoints.length);
    // Esto devuelve:
    // Orden: 3, Waypoints: 3

    while(i < waypoints.length){   
        var temp = "";

        temp += "<div id='"+waypoints[orden[i]].id+"' class='listaPedidos'>";
        temp += "<a href='DetallesServlet?id="+waypoints[orden[i]].id+"'>";
        temp += "<p>#"+waypoints[orden[i]].id+"</p>";
        temp += "<p>"+waypoints[orden[i]].desc+"</p>";
        temp += "<p>"+waypoints[orden[i]].dir+"</p>";
        temp += "</a></div>";

        div.innerHTML = temp;
        i++;
    }
}

What happens is that it only shows me 1 div with the information, the other 2 do not appear and I do not realize why it can be.

    
asked by Juan Manuel 09.12.2016 в 15:16
source

2 answers

2

Your variable temp always declared empty once you enter the cycle while , therefore the last record will always remain. This should be like this:

var temp = "";
while(i < waypoints.length){   
    temp += "<div id='"+waypoints[orden[i]].id+"' class='listaPedidos'>";
    temp += "<a href='DetallesServlet?id="+waypoints[orden[i]].id+"'>";
    temp += "<p>#"+waypoints[orden[i]].id+"</p>";
    temp += "<p>"+waypoints[orden[i]].desc+"</p>";
    temp += "<p>"+waypoints[orden[i]].dir+"</p>";
    temp += "</a></div>";

    div.innerHTML = temp;
    i++;
}
    
answered by 09.12.2016 / 15:19
source
2

I think it's that you're not concatenating the result:

var resultado = "";
while(i < waypoints.length){   
    var temp = "";

    temp += "<div id='"+waypoints[orden[i]].id+"' class='listaPedidos'>";
    temp += "<a href='DetallesServlet?id="+waypoints[orden[i]].id+"'>";
    temp += "<p>#"+waypoints[orden[i]].id+"</p>";
    temp += "<p>"+waypoints[orden[i]].desc+"</p>";
    temp += "<p>"+waypoints[orden[i]].dir+"</p>";
    temp += "</a></div>";

    resultado += temp;
    i++;
}
div.innerHTML = resultado;
    
answered by 09.12.2016 в 15:20