Reputation: 109
I declared javascript global variable in global.js file eg:
var glbValue;
and putting the value of global variable glbValue from first.html eg:
<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnSubmit()
{
glbValue=123;
}
</script>
and accessing the global variable glbValue from second.html eg:
<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnClick()
{
alert(glbValue);
}
</script>
it gives me output undefined inplace of 123, why ?
Upvotes: 1
Views: 132
Reputation: 18292
When a page loads, all its script files are executed in a new context. The browser does not 'remember' what you did in the last page. If you want to share a variable between pages, either you use cookies or, even better, localStorage
or sessionStorage
.
localStorage
if you want the value to be preserverd even when you close the browswer.sessionStorage
if you want the value to be preserved only during the current session. I think that the 2º solution is the best in your case:
first.html:
<script type="text/javascript">
function onBtnSubmit()
{
sessionStorage.setItem('gblValue', 123);
}
</script>
second.html
<script type="text/javascript">
function onBtnClick()
{
alert(sessionStorage.getItem('gblValue'));
}
</script>
You no longer need that global variable. The only problem with this solution is that IE8 and below do not support this, but there are good polyfills that use cookies transparently.
Upvotes: 2
Reputation: 12854
Try to use the local storage :
first.html :
localStorage.setItem("glbValue", "123");
second.html :
alert(localStorage.getItem("glbValue"));
Upvotes: 2