简体   繁体   中英

How to retain textbox values after navigating to other page?

I have a page(say register page) with text boxes in it. After entering values in them, if I navigate to other to page by using back and forward buttons in the browser and come back to the register page again. I want the entered text box values to be shown. Is there any way to do that. Hope somebody could help. Thanks in advance...

saving to local storage is a bit dangerous, because anyone can go to console and type: window.localStorage to see the saved values, for ALL USERS of the domain.

for example, on this page of SO right now, the localstorage contains this :

Storage {login-prefs: "{"provider":"google","oauth_version":"","oauth_server":"","username":""}",     se:fkey: "c6f10e10979159fee3220954ec846d68,1387300621", wb:isparticipating: "{"1106914":{"t":1387805621703,"v":false}}"}

assuming that the textbox values do not contain personal information, you will still need to address issue of multiple users on same machine.

one solution will be to use the user ID as a key, the value as a json representation of textboxId : value

example:

on window.befreunload event, strore all the textbox values under a key containing user ID:

localStorage.setItem( 'user_123_form-values' , JSON.stringify( [{ txbox1: 'some text' }, { txbox2: 'some other text' }]) );

to get values:

JSON.parse(localStorage['user_123_form-values'])

here is a fiddle to demonstrate the local storage approach, though if the data needs to be secure, you will need to use cookies:

http://jsfiddle.net/LLyB6/2/

JS variables never have been persistent, but there are two ways around this:

1.Cookies 2.Storage Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.

Instead, you should probably look at the Storage option.

Saving an item is as simple as localStorage.itemname = value ; Reading is as easy as localStorage.itemname , and deleting is as literal as delete localStorage.itemname

These values are saved across pageloads, but not sent to the server.

from:

Javascript global variable does not persist when navigate to another page (which also uses same js file)

What you are looking for is done using session / cookie / Appending query string:

Check this answer: PHP Pass variable to next page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM