1

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!

asked Apr 4, 2014 at 14:59

3 Answers 3

2

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.

answered Apr 4, 2014 at 15:11
Sign up to request clarification or add additional context in comments.

3 Comments

Only available in HTML5
Would it be possible to get more of an explanation on this?
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.
1

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

answered Apr 4, 2014 at 15:10

2 Comments

Thanks! But is there a variant without using cookies?
You have Local Storage but only in HTML5 html5samples.com/2010/04/simple-example-of-html5-local-storage
0

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

answered Apr 4, 2014 at 15:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.