dgamma3
dgamma3

Reputation: 2371

Simple javascript not working - frustrating!

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> 

Upvotes: -1

Views: 205

Answers (4)

Michael Blake
Michael Blake

Reputation: 2168

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

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

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';
}

Upvotes: 0

Michael Rose
Michael Rose

Reputation: 7820

Place the form before the script...

Upvotes: 0

Alnitak
Alnitak

Reputation: 339985

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...

Upvotes: 3

Related Questions