Calculate 2 numbers and display in the second input

Asked

Viewed 78 times

-1

When performing a calculation of 2 inputs I need the result to be displayed in the second input.

The result cannot appear on the third input, to perform the next calculation, field 02 cannot store the total value, you will need to store the entered value or the initial variable value.

Code:

function myFunction01(){ 
  var p1 = document.getElementById('demo01').value;
  var p2 = document.getElementById('demo02').value;
  document.getElementById("demo02").value = myFunction(p1,p2);
} 

function myFunction(p1, p2) {
  return p1 * p2; 
}
<!DOCTYPE html>
<html>
	<body>
		Espessura
		<input type="text" value="1.5" id="demo01">
		
		Raio da Dobra
		<input type="text" value="2" id="demo02">
		<button type="button" onclick="myFunction01()">clique</button>
	</body>
</html>

  • can put your code in the question showing what you have already done?

  • What do you mean? The result of the calculation should appear in the second input but it cannot save the value? Put also a [mcve].

  • 1

    What third input? Is the idea of the next calculation the same as the first calculation? I didn’t understand the goal.

  • The goal is to always keep the initial values of the varives, for example: 'lane 1 = 6, axis =2', 'lane 1 = lane 1 * axis ', then the calculation of lane 1 = 12, I want to clear this result of lane 1 and bring back the value of the previous variable, which is equal to 6, and also has to accept values typed by keyboard.

1 answer

0


Hello!

From what I understand the lightning will always be 2 but the result should be displayed in the lightning input, right?!

I will write a solution in pure javascript, without using the Jquery library.

function myFunction01() {
  let p1 = document.getElementById('demo01');
  let p2 = document.getElementById('demo02');
  const raio = 2;

  p2.value = myFunction(p1.value, p2.value);

  p1.addEventListener('click', function(){
      p2.value = raio;
  });
 
}

function myFunction(p1, p2) {
  return p1 * p2;
}
<!DOCTYPE html>
<html>

<body>
  <label for="demo01">Espessura</label>
  <br>
  <input type="text" value="1.5" id="demo01">

  <br><br>

  <label for="demo02">Raio da Dobra</label>
  <br>
  <input type="text" value="2" id="demo02">

  <br><br>

  <button type="button" onclick="myFunction01()">clique</button>
</body>

</html>

  • Thank you very much Victor, that’s what I needed.

  • You’re welcome to @Clodoaldodias, I’m happy to help you. If possible, mark the answer as the best answer to close the question. :)

Browser other questions tagged

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