javascriptparseint

parseInt returns NaN


spent 45min trying figure why it returns NaN, please point me to the right direction. My code is:

<form name="calc">
  <input type="text" value="0" name="first" onchange="add()">
  <input type="text" value="0" name="second" onchange="add()">
  <input type="text" name="result" onchange="add()">
</form>

<script type="text/javascript">
  var a = parseInt(document.calc.first.value);
  var b = parseInt(document.calc.second.value);
  var c = a + b;
  function add(){
    document.calc.result.value = parseInt(c);
  }
</script>


Solution

  • You're looking for:

    function add() {
      var a = parseInt(document.calc.first.value, 10);
      var b = parseInt(document.calc.second.value, 10);
    
      var c = a + b;
    
      document.calc.result.value = c;
    }
    

    You have to re-read a and b values each time they're changed.

    Note 1: Also, remember about radix parameter in parseInt(val, radix). It's 10 in your case (as I suppose). See this MDN article on why that's important.

    Note 2: no need to call parseInt(c), because c is already of the type number.