Execute function for various items in JS

0

I have a function that is responsible for updating the values in some <div> , script follows:

file.js

window.onload = function makeRequest() {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            calcPreco(xmlHttp.responseText);
    }
    xmlHttp.open("GET", "_config/buscar_valor.php?id="+document.getElementsByName("cloud")[0].getAttribute("cloudid")+"&periodicidade=monthly", true); // true para asynchronous 
    xmlHttp.send(null);
}

function calcPreco(preco) {
    console.log(preco);
    preco = preco.replace(",", ".");
    preco -= document.getElementsByName("cloud")[0].getAttribute("desconto");
    document.getElementsByClassName("mostrar_valor").textContent = preco;
}

index.php

<div name="cloud" cloudid="1" desconto="5"> 
<span class="mostrar_valor"></span> 
</div> 
<div name="cloud" cloudid="2" desconto="10"> 
<span class="mostrar_valor"></span> 
</div> 
<div name="cloud" cloudid="3" desconto="15"> 
<span class="mostrar_valor"></span> 
</div>

Note that only the attributes cloudid and desconto are changed in every <div> , the rest remain the same.

The script will only do a calculation looking for the value in "** search_value.php **", using the cloudid attribute, which is the ID of each plan.

The desconto attribute is the value that it will subtract from the account.

The problem is that it is doing this only for the first <div> , how can I make it work for all <div> ?

UPDATE:

window.onload = function calcPreco() {
for(const cloud of Array.from(document.getElementsByName("cloud"))) {
    fetch("_config/buscar_valor.php?id="+cloud.getAttribute("cloudid")+"&periodicidade=monthly")
     .then(res => res.text())
     .then(preco => {
        preco -= cloud.getAttribute("desconto");
        const valor = cloud.querySelector(".mostrar_valor");  
     })
    }
}
    
asked by anonymous 28.08.2018 / 15:36

1 answer

0

The problem is that you are only accessing the first div with the cloud attribute document.getElementsByName("cloud")[0]

In document.getElementsByName("cloud") you have a list of all the divs, so you will need a loop to go through this list.

Example:

// aqui guarda todas as divs com o atributo cloud    
var cloud_divs = document.getElementsByName("cloud"); 

// agora vamos aceder uma a uma através do ciclo for
for(let i; i < cloud_divs.length; i++){

valor = cloud_divs[i].getAtribute("desconto");
}

// uma versão mais simplificada
for( el of document.getElementsByName("cloud")){
    valor = el.getAtribute("desconto");
} 
    
28.08.2018 / 16:14