Reputation: 18997
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!
Upvotes: 1
Views: 20926
Reputation: 391
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
Upvotes: 0
Reputation: 7208
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.
Upvotes: 2
Reputation: 3683
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
Upvotes: 1