1

I want to extract a value from my hidden inputbox, by using javascript, but sometimes i am getting a "undefined" error and sometimes no output. when i did

alert(document.getElementById('hhh').value);

from inside a printIt() function i get the output. but i think somehow it is not going in to "var a", and also

var a =22; 

works if i remove the

var a =document.getElementById('hhh').value;

in below code.

<script type="text/javascript">
var a =document.getElementById('hhh').value;
function startTime()
{

document.getElementById('txt').innerHTML=a;
a=a-1;
t=setTimeout('startTime()',600);
}
</script>

<body    onLoad="startTime()">
<form name="form1"   id="form11" method="post" action="">
<input type="hidden" id="hhh" name="time" value="11" />
</form>
<div id="txt"></div>
</body>

Any help would be appreciated. Thanks.

1
  • 1
    Don't pass strings to setTimeout, pass functions instead. And don't use setTimeout for something you want to keep happening, use setInterval instead. setInterval(startTime, 600); Commented Feb 9, 2012 at 15:30

3 Answers 3

4

You call document.getElementById('hhh') before hhh exists. Move it into a function you call onload.

Sign up to request clarification or add additional context in comments.

2 Comments

if i move there, my var a will not get decremented.
In onload call a new function that does your setup - reading a etc then have it call setInterval(startTime,600);
3

var a =document.getElementById('hhh').value;

This runs before the document is loaded so the underlying element may not exist in the DOM.

You call document.getElementById('hhh') before hhh exists. Move it into a function you call onload.

var a;
function setup() {
    a = document.getElementById('hhh').value;
    startTime();
}
function startTime() {
    document.getElementById('txt').innerHTML = a--;
    setInterval(startTime, 600);
}

and run setup(); in your onload.

1 Comment

so how can i make it accessible without including it in the startTime(), as it won't get decremented then
2

Leave it as an "type=input" and add the css property: display: none;

<input type="input" id="hhh" name="time" value="11" style="display: none;" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.