change the value of inputs simultaneously when modifying one of them

1

In the following code I want that when modifying any of the 2 inputs change the other one with its respective operation but taking the variable from the one that has just been edited.

  function calcular()
  {
     var valor1=  parseFloat( document.getElementById("valor1").value); 
     var valor2=  parseFloat( document.getElementById("valor2").value);                           
     var valor3= document.getElementById("valor2").value = (4000*valor1)/2.25;  
     var valor4= document.getElementById("valor1").value = (3.56*valor2)/4000;  
  } 
<input type=text  id="valor1" onKeyUp="calcular();" />
<input type="text" id="valor2"  onKeyUp="calcular();" >

So when editing the field " valor1 ", automatically the field " valor2 " is: (4000*valor1)/2.25 without " valor1 "change also and vice versa

    
asked by Donjode 05.12.2018 в 19:53
source

2 answers

0

You need to pass the reference of the input that you are modifying. It would stay like this:

function calcular(input)
  {
     var id = input.id;
     if (id == "valor1") {
       document.getElementById("valor2").value = (4000*input.value)/2.25; 
     } else {
       document.getElementById("valor1").value = (3.56*input.value)/4000;  
     }
  }
<input type=text  id="valor1" onKeyUp="calcular(this);" />
<input type="text" id="valor2"  onKeyUp="calcular(this);" >
    
answered by 05.12.2018 / 20:01
source
0

I suggest you perform two functions, send to call the event onKeyUp according to the input where you are located, I leave the example with the same values that you used to make it clearer:

function calcular()
  {
     var valor1=  parseFloat( document.getElementById("valor1").value);                          
     var valor3= document.getElementById("valor2").value = (4000*valor1)/2.25;  
  }
  
  
  function calcularDos()
  {
     var valor2=  parseFloat( document.getElementById("valor2").value);                           
     var valor4= document.getElementById("valor1").value = (3.56*valor2)/4000;  
  }
<input type=text  id="valor1" onKeyUp="calcular();" />
<input type="text" id="valor2"  onKeyUp="calcularDos();" >

I hope it helps you. Greetings.

    
answered by 05.12.2018 в 20:02