You have two issues to solve:
- You need to be able to parse the multiple possible values that
window.navigator.language
can return.
- You need to alter the
select
option accordingly.
Parsing the language string
The first issue requires a (very slightly) more complex solution than testing if lang == "en"
.
English can be denoted by en
, but it can also be en-us
(American English), en-gb
(Great Britain), etc. Similarly German can be de
, de-ch
(Switzerland), de-at
(Austria), etc. Here's a helpful list of potential values.
So it's not going to work if you just test the raw value of lang
. The best solution seems to be to test only the first two characters of lang
, using lang.substr(0, 2)
.
Adjusting the selected option of #selectlang
Once you have the language string correctly parsed, you can change the selected option
using val()
.
Put the two together
var lang = window.navigator.userLanguage || window.navigator.language;
$("#selectlang").val(lang.substr(0, 2));