I have a defined global variable that I have tried to update a number of ways, but it does not work
<script>
var test = 4;
function dostuff() {
...
test=7;
or
window.test=7;
or
declare it here without the var = 7
...
}
</script>
then later...
<td><script type="text/javascript">document.write(test);</script></td>
output: 4!
Any help? Help me make it say 7!
Thanks
dostuff() is called like this.
$(document).ready(function(){
dostuff();
});
if I call it normally it does update the global variable correctly, but then other stuff in this program breaks. Any hint to update the global variable from within this $(document).ready(function()?
Thanks!
I am not sure where you are calling dostuff()
function, but there is one thing which need to be consider, if you want variable test
to be global for the page. Then you should declare it like this.
//this one is preferd
test = 4;
or
window.test = 4;
This should work, make sure you are calling dostuff()
.
Edit: Solving Function Call Problem
So here is complete solution with overview of your problem.
Problem: You are calling doStuff()
in document.ready()
(This got called after loading the DOM) event and you are printing the value of variable when DOM is loading.
It shows Old Value because doStuff()
is never got called before you printing the value in DOM.
Solution: There are two ways to achieve the desired output.
- Call
doStuff()
before starts loading (Right after its declaration). - Create a function, which do the calculation and return the value to be Print accordingly.
Solution 1:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
//Should be before Body tag
test = 4;
//Declaring function
function doStuff()
{
test = 8;
}
//Calling right after declarion
doStuff();
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
/*Here value is updated and ready to print any any where in the DOM*/
<h1><script type="text/javascript">
document.write(test);</script></h1>
</body>
</html>
Live URL to Solution 1
Solution 2:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
/*Should be before Body tag*/
test = 4;
function doStuff()
{
/*Changing value and returing it.*/
test = 8;
return test;
}
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h1><script type="text/javascript">
/*Calling function and printing returned value*/
document.write(doStuff());</script></h1>
</body>
</html>
Live URL to Solution 2
Hope this will help, let me know if any thing else is there, if nothing Accpet as answer!!