Skip to content
Advertisement

Remember selected value for next visits

I have a dropdown like this.

JavaScript

How can I show the selected value automatically at second time? First time it allows user to select an item from the drop down menu. But at second time it should show the previous selected value. How can I do this?

Advertisement

Answer

Your question is quite broad, so I will give you a short list of options:

Cookies

Session

In php you can save user data in a file, that is affiliated with ID saved in session cookie. PHP does all the stuff for you, all you need to do is to use the $_SESSION variable.
Let this be the form: form.php

JavaScript

Now, initally, $_SESSION is not even defined, so we must load the data from session:

load.php

JavaScript

And this is where the form submits:

save.php

JavaScript

Just cookies

Using just cookies allows user to change data anytime. This might be useful sometimes to handy users (but unfortunatelly for hackers too, if you’re not careful).
PHP automatically generates $_COOKIE array with all the cookies that are stored in users browser. (better said: that the user has sent)
I won’t make 3 file examples again, just see how cookies are created and deleted. Again, when setting a cookie, no output must come before the setcookie call.

JavaScript

Local storage

This solution won’t let your server know about user’s setting. It might not be compatible with older browsers.
Local storage saves information on user’s HDD without informing the remote server. Here’s a menu that remembers it’s selected value:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement