Multiply input values

Asked

Viewed 375 times

1

I was reading some tutorials and saw a Javascript function to add two inputs and show in real time. It works perfectly.

However, I would like to use it to multiply the values, however I could not modify the function, so when I make changes to the code I get an error.

function Soma(){
    var soma = 0;
    var ipts = document.querySelectorAll('input[oninput="Soma()"]');
    for(var x=0; x<ipts.length; x++){
       var valorItem = parseFloat(ipts[x].value);
       !isNaN(valorItem) ? soma += parseFloat(valorItem) : null;
    }
    document.querySelector('#final').value = soma.toFixed(2);
}
<form action="">
  Total produto1: <input type="text" oninput="Soma()" value="0"><br>
  Total produto2: <input type="text" oninput="Soma()" value="0"><br>
  <br>
  Total todos os produtos: <input type="text" id="final">
</form>

2 answers

1

The problem is that you were using the addition operator (+=). To multiply, you must use the multiplication operator (*=).

You can even simplify your code if you want:

const fields = document.querySelectorAll('.field')
const total = document.querySelector('#total')

function multiply() {
  let product = 1

  fields.forEach((field) => {
    let num = parseInt(field.value, 10)
    product *= isNaN(num) ? 1 : num
  })

  total.textContent = product
}

fields.forEach((field) => field.addEventListener('input', multiply))
<input type="number" class="field" />
<input type="number" class="field" />

<div>
  Total: <span id="total"></span>
</div>

To learn more, I suggest you check the pages referring to addition and multiplication.

  • Luiz Felipe, I changed the signs, but it wasn’t working here in my code. I appreciate the answers. Thank you very much personally!!

0


I made a change for it to multiply, but if you want to do the other operations will have to improve its function.

function Soma(){
    var soma = 0;
    var ipts = document.querySelectorAll('input[oninput="Soma()"]');
    for(var x=0; x<ipts.length; x++){
       var valorItem = parseFloat(ipts[x].value);
       if(soma ===0)
          soma = valorItem;
       else{
         !isNaN(valorItem) ? soma *= parseFloat(valorItem) : null;
         console.log(soma);
       }
    }
    document.querySelector('#final').value = soma.toFixed(2);
}
 <form action="">
  Total produto1: <input type="text" oninput="Soma()" value="0"><br>
  Total produto2: <input type="text" oninput="Soma()" value="0"><br>
  <br>
  Total todos os produtos: <input type="text" id="final">
 </form>

  • Thank you very much, you saved me!!!

  • Just changing the signal wasn’t working when I was making the modifications.

  • So this was happening because any value multiplied by 0 is 0, so it would never multiply by another value beyond zero, so I initialized it earlier with if ai worked.

Browser other questions tagged

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