Reputation: 23871
I have a choice:
<select id="selectlang">
<option value="en" selected>English</option>
<option value="de">Deutsch</option>
</select>
Now, I would like to set the default value by inspecting the browser's language.
var lang = window.navigator.userLanguage || window.navigator.language;
How can I modify the selection of a choice with jQuery?
Upvotes: 1
Views: 270
Reputation: 11391
You have two issues to solve:
window.navigator.language
can return.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));
Upvotes: 0
Reputation: 24322
Following code will work for you, but you have to change the value of the options kile
en => en-US because var lang = window.navigator.userLanguage || window.navigator.language;
will return the language code in the en-US
format
$("#selectlang").val(lang );
Upvotes: 1
Reputation: 1008
You can change the select value with jQuery like this:
$("#selectlang").val(lang);
but most likely you will need to validate the value of var lang = window.navigator.userLanguage || window.navigator.language;
Upvotes: 1
Reputation: 5625
You can select the value of a select box using jQuery's val() function:
$("#selectlang").val("en");
Upvotes: 1
Reputation: 6269
var lang = window.navigator.userLanguage || window.navigator.language;
if(lang === 'en-US')
$('#selectlang').val('en');
Also of note, IE (of course) doesn't support this property.
Upvotes: 2
Reputation: 8163
$('option:selected').attr('selected', false);
$('option[value="' + lang + '"]').attr('selected', true)
Upvotes: 0