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>
有帮助吗?

解决方案

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.

其他提示

a and b are calculated once at page load, when the form is still empty, obviously the result will be NaN.

Put all the logic in the add function, so you retrieve the current state of the form.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top