ceving
ceving

Reputation: 23871

How to change a choice selection with jQuery

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

Answers (7)

ASGM
ASGM

Reputation: 11391

You have two issues to solve:

  1. You need to be able to parse the multiple possible values that window.navigator.language can return.
  2. 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));

Upvotes: 0

Chamika Sandamal
Chamika Sandamal

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

MISJHA
MISJHA

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

Maloric
Maloric

Reputation: 5625

You can select the value of a select box using jQuery's val() function:

$("#selectlang").val("en");

Upvotes: 1

Eli
Eli

Reputation: 14827

You can do:

$("#selectlang").val(lang.split('-')[0]);

Fiddle

Upvotes: 4

jterry
jterry

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

imkost
imkost

Reputation: 8163

$('option:selected').attr('selected', false);
$('option[value="' + lang + '"]').attr('selected', true)

http://jsfiddle.net/nkVmV/2/

Upvotes: 0

Related Questions