I'm reading a book about JavaScript, but in a certain part the code in the book does not work.
The part is:
var qtyElements = produto[i].getElementsByClassName("quantity");
var qtyText = qtyElements[0].value;
var quantity = moneyTextToFloat(qtyText);
console.log(quantity);
It was to return the quantity of a class, however in the console I get NaN
.
Complete code:
function moneyTextToFloat(text){
var clean = text.replace("R$","").replace(",",".");
return parseFloat(clean);
}
function floatToMoney(value){
var text = (value < 1 ? "0" : 0 ) + Math.floor(value * 100);
text = "R$" + text;
return text.substr(0, text.length -2) + "," + text.substr(-2);
}
function readTotal(){
var total = document.getElementById("total");
return moneyTextToFloat(total.innerHTML);
}
function writeTotal(value){
var total = document.getElementById("total");
total.innerHTML = floatToMoney(value);
}
var totalProdutos = 0;
var produto = document.getElementsByClassName("produto");
for (let i = 0; i < produto.length; i++){
var priceElements = produto[i].getElementsByClassName("price");
var priceText = priceElements[0].innerHTML;
var price = moneyTextToFloat(priceText);
var qtyElements = produto[i].getElementsByClassName("quantity");
var qtyText = qtyElements[0].value;
var quantity = moneyTextToFloat(qtyText);
console.log(quantity);
}
<html>
<head>
<title>BIBLIOTECA</title>
<meta charset="utf-8">
</head>
<body>
<table>
<tbody>
<tr class="produto">
<td class="td"><div class="price">R$29,90</div></td>
<td><input type="number" class="quantity"></td>
</tr>
<tr class="produto">
<td><div class="price">R$59,90</div></td>
<td> <input type="number" class="quantity">
</td>
</tr>
<tr class="produto">
<td><div class="price">R$99,90</div></td>
<td><input type="number" class="quantity"></td>
</tr>
</tbody>
<tr>
<td></td>
<td>Total de compras</td>
<td><div id="total">R$ 189,90</div></td>
<td></td>
</tr>
</table>
<script type="text/javascript" src="JS/carrinhoDeCompra.js"></script>
</body>
</html>