Home > Back-end >  How to connect input with a and b?
How to connect input with a and b?

Time:12-06

How do I connect a with and connect b with ?

For example, If user key in 1st input, a will have the same value with 1st input.

and when user key in 2nd input, b will be the same value with 2nd input.

<!DOCTYPE html>
<html>
<body>



<input id="Number1" type="number">
 
<input id="Number2" type="number">
= 

<p id="demo"></p>

<script>
let a = 2;
let b = 3;
let c = a   b;
document.getElementById("demo").innerHTML = c;
</script>

</body>
</html>

CodePudding user response:

You probably want some event handler that can execute some code in response to specific events. You can have a button that calculates and outputs the answer:

<input id="Number1" type="number" />
 
<input id="Number2" type="number" />
=
<p id="demo"></p>
<button id="calculate">Calculate</button>

<script>
  function handleClick() {
    const num1 = document.getElementById("Number1").value;
    const num2 = document.getElementById("Number2").value;
    const answer = num1   num2;
    document.getElementById("demo").innerHTML = answer;
  }

  document.getElementById("calculate").addEventListener("click", handleClick);
</script>

Or you can add the event listener to run whenever the input values change.

<input id="Number1" type="number" value="0" />
 
<input id="Number2" type="number" value="0" />
=
<p id="demo"></p>

<script>
  function handleChange() {
    const num1 = document.getElementById("Number1").value;
    const num2 = document.getElementById("Number2").value;
    const answer = num1   num2;
    document.getElementById("demo").innerHTML = answer;
  }

  document.getElementById("Number1").addEventListener("change", handleChange);
  document.getElementById("Number2").addEventListener("change", handleChange);
</script>

These are very simple (and somewhat naive) implementations. For more advanced apps, you'll likely want to use some framework (e.g. React).

  • Related