Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to connect input with a and b?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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>

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading