How can I multiply and at the same time add these totals, where mi input
has the value value="2.500.000,00"
?.
I want to multiply and add without having to remove the points and decimals, since if I remove them my code works perfectly, but I want to do them with the points and decimals.
I am taking the value of the input
by means of the tr
.
Annex Fragment of my code
<!DOCTYPE html>
<html>
<body>
<table>
<thead>
<tr>
<th>Precio</th>
<th>Cantidad</th>
<th>Precio Total</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="text" class="input" value="2.500.000,00"> </td>
<td> <input type="number" class="input"> </td>
<td> <input type="text" class="total" disabled> </td>
</tr>
<tr>
<td> <input type="text" class="input" value="4.500.000,00" > </td>
<td> <input type="number" class="input"> </td>
<td> <input type="text" class="total" disabled> </td>
</tr>
<tr>
<td>TOTAL</td>
<td> <input type="text" class="totales" value="0" disabled> </td>
</tr>
</tbody>
</table>
</body>
</html>
<script>
var input=document.querySelectorAll(".input");
input.forEach(function(e) {
e.addEventListener("click",multiplica);
e.addEventListener("keyup",multiplica);
});
function multiplica() {
var tr=this.closest("tr");
var total=1;
var inputs=tr.querySelectorAll(".input");
inputs.forEach(function(e) {
total*=e.value;
});
tr.querySelector(".total").value=total.toFixed(2);
calcularTotal(this.closest("table"));
}
function calcularTotal(e) {
var total=0;
var totales=e.querySelectorAll(".total");
totales.forEach(function(e) {
total+=parseFloat(e.value);
});
e.getElementsByClassName("totales")[0].value=total.toFixed(2);
}
</script>
When performing the calculations you must "clean" values:
.replaceAll('.', '')
.replace(',', '.')
After that, it
2.500.000,00
will become a string that Javascript can interpret as a number:2500000.00
.Now, if the value of a field cannot be interpreted as a number, for example if it is an empty string, it
parseFloat()
will returnNaN
and you only need to add|| 0
to the end of the line to ensure that you have a numeric value.For more information, read the comments in the code:
In the end, if you want to maintain backwards compatibility with the number system you have implemented, you should run:
With this the output string will be
2.500.000,00
Recommendation: Declare your variables with
let
instead ofvar
to limit the context and avoid collisions or rewriting global variables.When you calculate the total you have for example:
Then you can use a Javascript method that is very straightforward with the thousands format: