Nigiri
Nigiri

Reputation: 3639

Are global variables stored in browser after the processing is ended?

Please see the following code.
After I clicked the button "PUT VAR", the alert always shows me the value "putted!!" when I click the button "SHOW VAR".
Does this mean that I can use global variables as hidden values on the page?

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript"> 
var test_var = "default";
$(function(){
    $("#show_var").on("click", function(){
        alert(test_var);
    });

    $("#put_var").on("click", function(){
        test_var="putted!!";
    });
});
</script>
</head>
<body>
<div id="demo">
<input type="button" value="SHOW VAR" style="width:100px" id="show_var" />
<input type="button" value="PUT VAR" style="width:100px" id="put_var" />
</div>
</body>
</html>

Upvotes: 0

Views: 211

Answers (1)

Zeta
Zeta

Reputation: 105905

Variables are stored as long as the context in which they were created is valid. Essentially

var test_var = value

outside of any closure is the same as

window.test_var = value.

The window object gets destroyed after a unload event, so as long as you stay in the same document context your variables are stored.

So, yes, you can use them as hidden values, but you should use <input type="hidden"> for form values.

Upvotes: 2

Related Questions