Error while adding javascript

Asked

Viewed 868 times

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?

2 answers

1


Your code is a bit confusing, but let’s see an example of why a sum might not work with Javascript.

The first point worth highlighting is that when we catch the value with Javascript it will return a string. To convert to a integer and can numerically sum these values you will need to use a function called parseInt().

Take this example without the parseInt():

function somarValores() {
  let s1 = document.getElementById("txt1").value;
  let s2 = document.getElementById("txt2").value;
  let s3 = document.getElementById("txt3").value;
  let resposta = (s1 + s2 + s3);
  alert(resposta);
}
<fieldset>
  <legend>Cálculo de soma sem utilizar o parseInt</legend>
  <p>
    <label>Valor 1:</label>
    <input id="txt1" type="number" />
  </p>
  <p>
    <label>Valor 2: </label>
    <input id="txt2" type="number" />
  </p>
  <p>
    <label>Valor 3: </label>
    <input id="txt3" type="number" />
  </p>
  <button id="somar" onclick="somarValores()">Somar</button>
</fieldset>

By typing, for example, 10 in the first field, 10 in the second and third we will have the value: 101010. What happened is that he concatenou as strings, did not add.

Now look at this example with the parseInt():

function somarValores() {
  let s1 = parseInt(document.getElementById("txt1").value);
  let s2 = parseInt(document.getElementById("txt2").value);
  let s3 = parseInt(document.getElementById("txt3").value);
  let resposta = (s1 + s2 + s3);
  alert(resposta);
}
<fieldset>
  <legend>Cálculo de soma utilizando o parseInt</legend>
  <p>
    <label>Valor 1:</label>
    <input id="txt1" type="number" />
  </p>
  <p>
    <label>Valor 2: </label>
    <input id="txt2" type="number" />
  </p>
  <p>
    <label>Valor 3: </label>
    <input id="txt3" type="number" />
  </p>
  <button id="somar" onclick="somarValores()">Somar</button>
</fieldset>

See, by adding 10 + 10 + 10 we have the result as 30, which would be correct.

Based on your code you could edit this part for a parseInt().

calc_quant_total_produto += parseInt(quant_produto[i].value);

Beyond the parseInt() there is also the parseFloat() for numbers that are not integers.

References:

  • 1

    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.

  • 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, 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.

  • 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, 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.

  • I get it. Thank you all for your help.

Show 1 more comment

0

Possibly the values are of the type 'text', therefore the concatenation .

for(var i=0;i<tam_grade_produto.length;i++){
  var quantProduto = parseInt(quant_produto[i].value);
  calc_quant_total_produto+= quantProduto;
}

If you wanted to convert to decimal, use: parseFloat()

  • 1

    Exactly and worth remembering @Bruno that you are catching selectorAll of "id" and id does not repeat, instead use class

  • I don’t understand what you said about "id" not repeating. In the excerpt of the code I showed is inside a loop that generates several inputs with the same id, so it repeats yes, so the use of selectorAll. I just didn’t post here the entire html code that.

  • The id is used to identify only 1 element while class is for several, from a look http://tableless.github.io/beginnertes/manual/css/class-id.html or you can consult W3 @Bruno It may work there, but there will be situations where it will not work, I’ve been through several, he will always take the last element with the same id, in your case he took them all with that id and so on, but if you use byId it would be confusing so start to see the difference between class and id

Browser other questions tagged

You are not signed in. Login or sign up in order to post.