0

can someone please help me get this simple countdown timer to work, firebug is complaining: document.counter is undefined

<script> 
<!-- 
// 
 var milisec=0 
 var seconds=30 
 document.counter.d2.value='30' 

function display(){ 
 if (milisec<=0){ 
    milisec=9 
    seconds-=1 
 } 
 if (seconds<=-1){ 
    milisec=0 
    seconds+=1 
 } 
 else 
    milisec-=1 
    document.counter.d2.value=seconds+"."+milisec 
    setTimeout("display()",100) 
} 
display() 
--> 
</script> 


<form name="counter"><input type="text" size="8" 
name="d2"></form> 
dgamma3
  • 2,333
  • 4
  • 26
  • 47

4 Answers4

4

indeed, document.counter doesn't exist because your script is being called before the HTML DOM is loaded.

You need to put your JS inside a function that will be invoked onload.

Instead of calling display() put this at the bottom of your script:

window.onload = display;

Also, the <!-- --> comments haven't been needed around JS code for at least 10 years...

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • You may also find the following discussion usefull: [Best Practice: Access form elements by HTML id or name attribute](http://stackoverflow.com/questions/2435525/best-practice-access-form-elements-by-html-id-or-name-attribute)? – Fábio Apr 11 '11 at 12:33
0

Place the form before the script...

Michael Rose
  • 7,770
  • 3
  • 22
  • 26
0

Either have the script at the end of the page, or:

window.onload = function() {
   var milisec=0;
    var seconds=30 ;
    document.forms["counter"].elements["d2"].value='30';
}
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

You might want to move to JQuery to help with cross browser issues
JQuery $(document).ready()

Michael Blake
  • 2,068
  • 2
  • 18
  • 31