In general I did a routine that can be easily adapted to any type of operation and amount of fields.
Just add the fields, retrieve the values and make the proper calculations on the variable total
//formata o resultado para reais e decimais com virgula
function reais(n) {
var l = Math.floor(n);
var r = Math.round((100*n)%100);
if (r<10) return "R$"+l+",0"+r;
if (r==100) return "R$"+(l+1)+",00";
return "R$"+l+"."+r;
}
function calculate(f) {
//retorno dos valores dos campos
var id1=document.getElementById('id1').value;
var id2=document.getElementById('id2').value;
var id3=Number(document.getElementById('id3').value);
var id4=document.getElementById('id4').value;
var id5=document.getElementById('id5').value;
//para não invalidar o resultado caso haja alguma divisão no total
if(id5==""){
id5=1;
}
//aqui as operações envolvendo os campos
var total=(((id1*id2)+id3)-id4)/id5;
f.total.value=reais(total);
}
<form>
Quantidade
<input type="text" name="input1"t id="id1">
Preço Unitário
<input type="text" name="input2" id="id2"><br>
Imposto
<input type="text" name="input3" id="id3"><br>
Desconto
<input type="text" name="input4" id="id4"><br>
Parcelas
<input type="text" name="input5" id="id5">
<p>
<table>
<tr><td>
Resultado:</td><td><input type=text name=total size=8>
</td></tr>
</table>
<p>
<input type=button value=Calculate onClick="calculate(this.form);">
</form>
The +
operator may surprise you depending on the way you use it.
- Everyone knows that the
+
operator serves for at least two things: adding numbers and concatenating strings!
- In the example of the response the variable
var id3
was transformed into a number with the function Number
to perform the addition operation because otherwise there would be a concatenation.
Instead of using the Number
function in the variable var id3
we could use the +
operator itself to convert it to a number.
See how:
Instead of:
var id3=Number(document.getElementById('id3').value);
Use
var id3=document.getElementById('id3').value;
And replace var total
with
var total=(((id1*id2)+(+id3))-id4)/id5;
Example
//operador + para conveeter em numero
console.log(10 + +'10');
//sem o operador +
console.log(10 + '10');