简体   繁体   中英

Javascript or jQuery to select a option in select element

I am wanting to automatically select the option with the value of fr.

<select class="goog-te-combo">

<option value="">Select Language</option>
<option value="fr">French</option>

</select>

Is this possible with javascript or jQuery ?

设置法语选项:

$('.goog-te-combo').val("fr");

Without jQuery you need brute force

var country="fr";
//If you know the form and name of the select:
var sel = document.forms[0].sel1;

//If you know the id of the select:
var sel = document.getElementById('sel1');

// If you only know the className:
var sels = document.getElementsByTagName('select');
for (var i=0,n=sels.length;i<n;i++) {
  if (sels[i].className=="goog-te-combo") { // assume multiple selects with same class
    for (var j=0, m=sels[i].options.length;j<m;j++) {
      if (sels[i].options[j].value==country) sels[i].options[j].selected=true;
    }
  }
}

以下代码段还将设置fr选项:

$('option[value="fr"]').attr({selected: 'true'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM