I saw this post - Saving dropdown menu selection in a cookie?. I got a dropdown menu which has 2 languages in it and when I press on one of them it changes the language, but the problem was, it always selects the top entry after refreshing the page. Using the code in the link the selected value remains selected after page refresh, but now when I press the desired language it does nothing. The link doesn't work anymore.
Here it is:
<select name="change" id="change">
<option value="en" href="@Url.Action("ChangeCulture", "Home", new { lang = "en" })">English</option>
<option value="de" href="@Url.Action("ChangeCulture", "Home", new { lang = "de" })">Deutsch</option>
</select>
And the script with the cookie:
<script>
function saveTheme(cookieValue) {
var sel = document.getElementById('ThemeSelect');
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + sel.value;
setCookie('theme', cookieValue, 365);
}
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays == null || nDays == 0)
nDays = 1;
expire.setTime(today.getTime() + 3600000 * 24 * nDays);
document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
document.addEventListener('DOMContentLoaded', function () {
var themeSelect = document.getElementById('ThemeSelect');
var selectedTheme = readCookie('theme');
themeSelect.value = selectedTheme;
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + selectedTheme;
});
</script>
Edit: When I add this code from this link: Links in <select> dropdown options, the language is changed as it should be, but the problem now is that after the button is pressed, the selected language doesn't stay visible on top of the dropdown menu. This is the code I added in addition to the other code in the script:
document.getElementById('ThemeSelect').onchange = function () {
window.location.href = this.children[this.selectedIndex].getAttribute('href');
}