How to multiply the value of 3 inputs using pure javascript?

1

I'm trying to multiply 3 fields, the total value will be returned in a new label. But I can not. When I did with 1 field only, it worked:

link

I even tried to if (isNaN( but it did not work. No error, but it does not work!

    
asked by anonymous 19.05.2014 / 15:32

2 answers

4

Change your total variable:

 var Total = document.getElementById(comprimentoID).value * document.getElementById(LarguraID).value * document.getElementById(InclinacaoID).value;

The problem is that you are passing to the function the ID of the field that contains the value that needs to be multiplied.

Also change the onChange event of each field, instead of passing the filled-in value in the field length, passes the field ID:

<input id="txt_Comprimento_1"  type="number"   onchange="MudaPreco('txt_Comprimento_1','txt_Largura_1','txt_Inclinicacao_1','PrecoProd_1')" /><br>
<input id="txt_Largura_1" type="number" onchange="MudaPreco('txt_Comprimento_1','txt_Largura_1','txt_Inclinicacao_1','PrecoProd_1')"   /><Br>
<input id="txt_Inclinicacao_1" type="number" onchange="MudaPreco('txt_Comprimento_1','txt_Largura_1','txt_Inclinicacao_1','PrecoProd_1')"  /><br><br>
    
19.05.2014 / 15:47
4

Your problem is that when you do onchange you are always passing two strings, soon you will multiply the value of the input you are passing (properly) two strings.

Your error was:

onchange="MudaPreco(this.value,'txt_Largura_1','txt_Inclinicacao_1','PrecoProd_1')

And what the function was going to receive was:

function MudaPreco(4, txt_Largura_1, txt_Inclinicacao_1, PrecoProd_1)

So when you computed the var Total it would be:

var Total = 4* txt_Largura_1* txt_Inclinicacao_1

Here's what I advise you to do:

    comprimentoID = $('#txt_Comprimento_1').val();
    LarguraID = $('#txt_Largura_1').val();
    InclinacaoID = $('#txt_Inclinicacao_1').val();

    var Total = comprimentoID * LarguraID * InclinacaoID;

I leave JSFIDDLE with an example resolution.

EDIT: No JQuery

You can use document.getElementById('txt_Comprimento_1').value which is native to javascript.

LINK without jquery.

    
19.05.2014 / 15:39