I have a textfield:
<input id='textfield'>
And have a script in <head>, to get text from text field
function save(){
var text_to_save=document.getElementById('textfield').value;
}
I would like to save it (var text_to_save) so as user will see the same text if he reload (or reopen) the page.
Thanks!
Add a comment
|
3 Answers
you can use local storage for this:
function save(){
var text_to_save=document.getElementById('textfield').value;
localStorage.setItem("text", text_to_save); // save the item
}
Now when you reload the page you could retrieve the saved data and display it as follows:
function retrieve(){
var text=localStorage.getItem("text"); // retrieve
document.getElementById('textDiv').innerHTML = text; // display
}
a 'variant', as you put it.
3 Comments
csharpwinphonexaml
Only available in HTML5
Steve Byrne
Would it be possible to get more of an explanation on this?
Anubhav
Sure. the
function save() saves the item. First we declare a variable which stores the value of the text field using localstorage. Now if you want to retrieve the stored data you first use another variable to first get the stored data using the .getItem() and store it. Then you display the the text using .innerHTML. I find it much easier to use jQuery rather than pure javascript. Hope it helps.You could try using cookies
Example
Save value to cookie:
document.cookie ='text_to_save='+text_to_save+';';
Read previously saved value:
var saved_text = document.cookie;
document.getElementById('textfield').value=saved_text;
Find out more about cookies here http://www.w3schools.com/js/js_cookies.asp
2 Comments
nicael
Thanks! But is there a variant without using cookies?
csharpwinphonexaml
You have Local Storage but only in HTML5 html5samples.com/2010/04/simple-example-of-html5-local-storage
You could do this like below:
function getCookieByName( name )
{
var cookies = document.cookie,
cookie = cookies.match( '/' + name + '=(.+);/' ),
match = cookie[0];
return match;
}
var textToSave = document.getElementById('textfield').value;
document.cookie = 'mySavedText=' + textToSave;
mySavedText is the cookie name, so you could then run the function:
getCookieByName( 'mySavedText' );
and it should return the text you wanted to save.
For more information on cookie handling in Javascript check out the MDN article on it