I've seen this posted a few times, but I wasn't able to get the code working at all. I need help making this drop down menu save its settings to a cookie, so when the user visits the site again, their previous selection is retained.
Dropdown:
<select id="ThemeSelect">
<option value="zelda">Zelda</option>
<option value="smb2">SMB 2</option>
</select>
For reference, this code is with some Javascript in a Wordpress widget that changes the css code, like a theme selector.
How would I make this save as a cookie? I feel like I've tried everything!
EDIT: I should have said, but I use this code to change the CSS:
var saveclass = null;
var sel = document.getElementById('ThemeSelect');
sel.onchange = function(){
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + sel.value;
};
Note: This answers adds to Josh Mein's answer. Feel free to merge it.
We can get the cookie using this function, shamelessly stolen from this question.
Then we need to select the value when the page loads. The following code will accomplish just that.
You should look into creating Session variables in PHP.
http://www.w3schools.com/php/php_sessions.asp
You can save variables to a session and when you load the page, you check the value of the variable you set, depending on it's value, the dropdown could behave a certain way. Maybe store the name of the dropdown item as a session variable?
Something along these lines should work for you. The function to create a cookie via javascript was found in Setting a Cookie from JavaScript, a post on javascripter.net.
HTML:
Javascript:
Edit:
Save the cookie
I have merged the two functions into one for you.
HTML:
Javascript:
Live DEMO
Read the cookie on return to the page
Thanks to dunsmoreb
We can get the cookie using this function, shamelessly stolen from this question.
Then we need to select the value when the page loads. The following code will accomplish just that:
Live DEMO