-1

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>
showdev
  • 28,454
  • 37
  • 55
  • 73

1 Answers1

0

First error is in select itself onchange="changeLang()" while the function name in script is checkLang()

Second thing is you are referring to option tag incorrectly, instead of this

// There is no tag called "value"
document.getElementById("lang").getElementsByTagName("value")["english"].selected = "selected";

it should be like this

// 0 here points to the first option tag
document.getElementById('lang').options.selectedIndex = 0;

Or like this

document.getElementById("lang").options[0].selected = 'selected';

Or if you want to keep you logic you have to modify it to work

// the tag name here is "option" not "value"
// point to a certain option tag using the index i.e. 0,1,2,...
document.getElementById("lang").getElementsByTagName("option")[0].selected = "selected";

If you would like to perform this function every time the page loads to detect the language from URL and set the select with current language then your body tag should be like this <body onload="checkLang();"> and remove onchange="checkLang();" from select tag

Hossam Houssien
  • 359
  • 4
  • 14