Hy2703 Hy2703 - 2 months ago 7
Javascript Question

javascript manual timer - the script is giving error : (TypeError: Cannot read property 'value' of null)

i don't understand why it is not taking value, it is giving type-error cannot take null value in console log



var seconds = parseInt(document.getElementById('secs').innerHTML);
var timer;

function countdown() {
var container = document.getElementById('dl');
seconds--;
if (seconds > 0) {
container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
} else {
container.innerHTML = 'Time over';
clearInterval(timer);
}
}

<!-- <div id="dl"></div>
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Start" /> -->

<input type="text" id="secs" placeholder="enter seconds" />
<input type="button" onclick="setInterval(countdown, 1000);" id="dl" value="Start" />
<div id="dl"></div>




Answer

A few things:

  1. input elements don't have a useful innerHTML, they have value.

  2. You're trying to read from the input right away when your script runs. You want to wait until the user clicks the button.

  3. You're never saving the interval's handle to timer

  4. You have two elements with the id "dl". You can only have one element with a given id in the document.

See comments for where each is corrected below:

// #1: Wait for user to click the button before reading the value
// Note we're using modern event handling, rather than onxyx attributes
document.getElementById("dl").addEventListener("click", function() {
  // #2: Use `value`, not `innerHTML`, with `input` elements
  var seconds = parseInt(document.getElementById('secs').value);
  // #3: Save the interval's handle to `timer`
  var timer = setInterval(countdown, 1000);

  function countdown() {
    var container = document.getElementById('count');
    seconds--;
    if (seconds > 0) {
      container.innerHTML = 'Please wait <b>' + seconds + '</b> seconds..';
    } else {
      container.innerHTML = 'Time over';
      clearInterval(timer);
    }
  }
}, false);
<input type="text" id="secs" placeholder="enter seconds" />
<input type="button" id="dl" value="Start" />
<!-- #4: Use a different ID for the timer output -->
<div id="count"></div>


You might also consider showing a message right away when the user clicks, instead of waiting for that first second. I'll leave that as an exercise for the reader...

Comments