-5

I've a practical assignment for middle school, to make a simple Javascript website. But I keep getting a NaN on my website. I can't figure out why. Mayby some-one understands what I do wrong. Thanks by forehand.

var timer = setInterval(time, 5000);

function time() {
  document.getElementById('change').innerHTML = Date();
}
var calculate = setInterval(calcFunction, 5000);
function calcFunction(inputValue, change) {
  var answer = Number(inputValue) + 1;
  document.getElementById('answer').innerHTML = answer;
}
<input type="text" id="inputValue">
<p id="answer"></p>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • `NaN` is not an error, it's a value. Make sure you're doing the math with numbers, and not with elements or undefineds. – Teemu Jan 13 '22 at 10:58
  • 4
    `inputValue` is always `undefined` (the same for `change`) – Andreas Jan 13 '22 at 10:58
  • is this all your code? I don't see any element with id 'change'. Could you help me understand what is it that you are trying to acheive? – TheWhiteFang Jan 13 '22 at 11:02
  • Just because you have an _element_ with the id `inputValue` does not make the _variable_ `inputValue` has its value. you need to read the value inside of `calcFunction` – Jamiec Jan 13 '22 at 11:02
  • @Jamiec Indeed, having an element with `id="inputValue"` does not automatically give its value, but it does expose the DOM element itself, interestingly. One can do `inputValue.value` directly, without `getElementById`. – Jeremy Thille Jan 13 '22 at 11:11
  • 1
    @JeremyThille indeed, but it's [not a good idea](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) – Jamiec Jan 13 '22 at 11:13

1 Answers1

-1

You need the value of the inputValue inside the calcFunction

var timer = setInterval(time, 5000);

function time() {
  document.getElementById('change').innerHTML = new Date().toLocaleDateString();
}
var calculate = setInterval(calcFunction, 5000);

function calcFunction() {
  var answer = Number(document.getElementById("inputValue").value) + 1;
  document.getElementById('answer').innerHTML = answer;
}
time()
calcFunction()
<span id="change"></span><br/>

<input type="text" id="inputValue">
<p id="answer"></p>
mplungjan
  • 169,008
  • 28
  • 173
  • 236