Search code examples
javascripthtmlerror-handlingfrontendnan

Why is output value shown as NaN


The code is supposed to find the sum of two times entered in hours and minutes but it gives me the output "NaN".

function add() {
  var min, hrs;
  let a = Number(document.getElementById("first"));
  let b = Number(document.getElementById("third"));
  let c = Number(document.getElementById("second"));
  let d = Number(document.getElementById("fourth"));
  min = c + d;
  hrs = min / 60;
  min = min % 60;
  hrs = hrs + a + b;
  document.write(hrs);
  document.write(min);
}
<h1>Time Calculator</h1>
<h2>This calculator can be used to “add” two time values.</h2>
Enter hours: <input id="first"> 
Enter Minutes: <input id="second"> 
Enter hours: <input id="third"> 
Enter Minutes: <input id="fourth">
<button onclick="add()">ADD</button>


Solution

  • You're missing value calls on the getElementByIds! So:

      let a = Number(document.getElementById("first").value);
      let b = Number(document.getElementById("third").value);
      let c = Number(document.getElementById("second").value);
      let d = Number(document.getElementById("fourth").value);
    

    Quick recommendation: Add type="number" to the inputs to ensure that the inputs are numbers.

    <h1>Time Calculator</h1>
    <h2>This calculator can be used to “add” two time values.</h2>
    Enter hours: <input id="first" type="number"> 
    Enter Minutes: <input id="second" type="number"> 
    Enter hours: <input id="third" type="number">  
    Enter Minutes: <input id="fourth" type="number">
    <button onclick="add()">ADD</button>
    

    Full code:

    function add() {
      var min, hrs;
      let a = Number(document.getElementById("first").value);
      let b = Number(document.getElementById("third").value);
      let c = Number(document.getElementById("second").value);
      let d = Number(document.getElementById("fourth").value);
      min = c + d;
      hrs = min / 60;
      min = min % 60;
      hrs = hrs + a + b;
      document.write(hrs);
      document.write(min);
    }