When a page is loaded, I would like it to set the correct value for the <select>
box. I did this by using onload
on the body to call a function, I then got the url and extracted the language from the url (e.g http://example.com/en/index.html is now 'en'). Once I have this, I am then trying to change the selected value for the select box to the appropriate tag. However, when using Chrome, I can see that it attempts to change but around half a second later it then flips back over to the default ("English"). What am I doing wrong?
I have also tried .selected = true;
to no avail.
function checkLang() {
var url = location.href;
var curLang = url.substring(0, url.lastIndexOf('/'));
curLang = curLang.substr(curLang.length - 2);
if (curLang == "en") {
document.getElementById("lang").getElementsByTagName("value")["english"].selected = "selected";
} else if (curLang == "fr") {
document.getElementById("lang").getElementsByTagName("value")["french"].selected = "selected";
} else if (curLang == "de") {
document.getElementById("lang").getElementsByTagName("value")["german"].selected = "selected";
} else if (curLang == "es") {
document.getElementById("lang").getElementsByTagName("value")["spanish"].selected = "selected";
}
}
<select id="lang" onchange="changeLang()" autocomplete="off">
<option value="english">English</option>
<option value="spanish">Spanish</option>
<option value="french">French</option>
<option value="german">German</option>
</select>