Search code examples
javascripthtmlonkeyup

I want to show addition of two number without using any button


I have two input boxes with id no1 and no2. I have to put two integer values on both inputs and show their sum without using any button. My code works, but it shows only the individual values, not the calculated sum.

How can I show my addition value In real time when user is just typing?

var c;
var a = document.getElementById("no1");
var b = document.getElementById("no2");
var number = document.getElementById("number");
var m = document.getElementById("message");

a.onfocus = function() {
  m.style.display = "block";
}

a.onblur = function() {
  m.style.display = "none";
}

a.onkeyup = function() {
  var c;
  if (isNaN(a.value) == false) {
    c = a.value + b.value;
    m.innerHTML = c;
  } else {

    m.innerHTML = "<font color='red' size='45px'><strong>Must containe number only</strong></font>";
  }
}
b.onfocus = function() {
  m.style.display = "block";
}
b.onblur = function() {
  m.style.display = "none";
}
b.onkeyup = function() {

  if (isNaN(b.value) == false) {
    c = a.value + b.value;
    m.innerHTML = c;
  } else {

    m.innerHTML = "<font color='red' size='45px'><strong>Must containe number only</strong></font>";
  }
}
<div class="container">
  <input type="text" id="no1" name="no1" />
  <input type="text" id="no2" name="no2" />
  <button onclick="myFun()">Press Me</button>
</div>

<center>
  <font color="blue" size="45px" id="message"></font>
</center>


Solution

  • var c; 
    var a = document.getElementById("no1"); 
    var b = document.getElementById("no2"); 
    var number = document.getElementById("number"); 
    var m = document.getElementById("message"); 
    a.onfocus = function() { 
    m.style.display = "block"; } 
    a.onblur = function() { 
    m.style.display = "none"; } 
    a.onkeyup = function() { 
    var c;
    if (isNaN(a.value) == false) { 
    c = Number(a.value) + Number(b.value); 
    m.innerHTML = c; 
    }
    else { 
    m.innerHTML = "<font color='red' size='45px'><strong>Must containe number only</strong></font>";
    }
    }
    b.onfocus = function() { 
    m.style.display = "block"; } 
    b.onblur = function() { 
    m.style.display = "none"; } 
    b.onkeyup = function() { 
    
    if (isNaN(b.value) == false) { 
    c = Number(a.value) + Number(b.value); 
    m.innerHTML = c;
    } 
    else { 
    m.innerHTML = "<font color='red' size='45px'><strong>Must containe number only</strong></font>"; 
    }
    }