最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTML - Save data from text field with javascript - Stack Overflow

programmeradmin5浏览0评论

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!

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!

Share Improve this question asked Apr 4, 2014 at 14:59 nicaelnicael 19k13 gold badges62 silver badges92 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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./js/js_cookies.asp

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

发布评论

评论列表(0)

  1. 暂无评论