2011-04-15 80 views
19

我有一個下拉菜單,我無法弄清楚如何使javascript函數選擇一個下拉菜單選項。我已經測試了變量的輸出,它們都是正確的,但點擊時它仍然不會選擇該選項。這是功能和下拉菜單。使用javascript選擇下拉菜單選項

功能

function formFill(a, b, c){ 
     theform.from.value = a; 
     theform.to.value = b; 
     for(var i = 0;i < document.getElementById("stateSelect").length;i++){ 
      if(document.getElementById("stateSelect").options[i].value == c){ 
       document.getElementById("stateSelect").selected = true; 
      } 
     } 
    } 

菜單項

<select id="stateSelect" name="stateSelect"> 
    <option value="none">(None)</option> 
    <option value="AL">Alabama</option> 
    <option value="AK">Alaska</option> 
+1

您不應該重複`document.getElementById(「stateSelect」)`。調用一次並將參考存儲在變量中。 – RoToRa 2011-04-15 14:42:02

+0

請參閱這篇文章:http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/ – 2016-05-25 12:18:19

回答

29

更改讀取行:

document.getElementById("stateSelect").selected = true;

到:

document.getElementById("stateSelect").selectedIndex = i;

12

Alt。你可以設置選擇的實際選項:select.options [i] .selected = true;

... 
     var select = document.getElementById("stateSelect"); 
     for(var i = 0;i < select.options.length;i++){ 
      if(select.options[i].value == c){ 
       select.options[i].selected = true; 
      } 
     } 
...