0
I have a code that dynamically generates several inputs. In addition I have a function that should add the value informed within the inputs. The problem is that instead of adding it together it concatenates the fields. The strange thing is that I did the same process elsewhere and the sum works.
Javascript code:
var tam_grade_produto = document.querySelectorAll("#tam_grade_produto");
var quant_produto = document.querySelectorAll("#quant_produto");
var quant_total_produto = document.querySelector("#quant_total_produto").value;
function preencheTotalProduto(){
var calc_quant_total_produto = 0;
for(var i=0;i<tam_grade_produto.length;i++){
calc_quant_total_produto += quant_produto[i].value;
}
quant_total_produto.textContent = calc_quant_total_produto;
}
document.addEventListener("onchange",function(event){
event.preencheTotalProduto();
});
preencheTotalProduto();
The code below is inside a for
and generates fields I need:
<tr>
<td><kbd><label id="tam_grade_produto"><?= $tamanho['tamanho']; ?></label></kbd></td>
<td><input size="3" class="form-control" id="quant_produto" type="number" onchange="preencheTotalProduto()" min="1" max="<?= $tamanho['estoque']; ?>"></td>
<td><input size="3" readonly="true" class="form-control" type="number" onchange="preencheTotalProduto()" value="<?= $tamanho['estoque']; ?>"></td>
</tr>
And that’s the chunk of code that should hold the sum:
<div>Total de pares: <label id="quant_total_produto">0</label></div>
But when filling the value of a 3 inputs with the values of 1, 2 and 3, for example, in the total of pairs does not appear 6 but 0123. It feels like it’s concatenating instead of adding up. Does anyone know how to say?
I advise to change the references to the MDN that is more reliable: parseint and parseFloat. It is also worth remembering that it is important to pass the second parameter to parseint to avoid implementation inconsistency of browsers.
– fernandosavio
It worked by adding parseint() to the value. But I also had to put a default value in html as well because I think the sum was null when adding some field that was blank. <input size="3" class="form-control" id="quant_product" type="number" onchange="fillTotalProduct()" min="1" max="<?= $size['stock'];? >" value="0">
– Bruno
@Bruno, you could do a little validation before with Javascript to see if the fields were really filled in. Also the question of
value="0"
can resolve, if fields are not mandatory.– João Pedro Schmitz
But some fields really do not need to be filled in. Here for me the question is solved. But I don’t know how to mark the topic as solved.
– Bruno
@Bruno, if the answer has solved your problem you can mark as accepted by clicking on the green V side of the chosen points. If you wish, you can also vote in favour.
– João Pedro Schmitz
I get it. Thank you all for your help.
– Bruno