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");
})
}
}