What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the
You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.
Cookie *Create and Store a Cookie:*
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The function which will return the specified cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i
Display a welcome message if the cookie is set
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.
Jquery
Set a value to the session storage.
Javascript:
$.sessionStorage( 'foo', {data:'bar'} );
Retrieve the value:
$.sessionStorage( 'foo', {data:'bar'} );
$.sessionStorage( 'foo' );Results:
{data:'bar'}
Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:
var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);
//...
var storedNames=JSON.parse(localStorage['names']);
Server Side Example using ASP.NET
Adding to Sesion
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
// When retrieving an object from session state, cast it to // the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
I hope that answered your question.