2
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 amount of a class, but in the console returns me 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>
Inputs have no value so it returns Nan. Put
values
in inputs, ex:value="10"
gets like this<input type="number" class="quantity" value="10">
– user60252
That’s what Grandpa @Leocaracciolo said, but to avoid Nan, put a Short circuit evaluation in the variable:
var qtyText = qtyElements[0].value || '0';
. So if the field is empty, it will be equal to0
.– Sam