2012-04-02 75 views
0

我有以下的下拉列表:動態地選擇值從下拉列表中

我想:

document.getElementById('select_value').selected ="val3"; 

<select name="selSS1" id="select_value"> 
    <option value="val0">sea zero</option> 
    <option value="val1">sea one</option> 
    <option value="val2">sea two</option> 
    <option value="val3">sea three</option> 
    <option value="val4">sea four</option> 
</select> 

我想使用JavaScript動態地選擇從該列表中的值

但上面的代碼似乎不工作。任何幫助最受讚賞。

+0

你必須要熟悉JavaScript方法和性能 – AmGates 2012-04-02 12:04:59

+0

請檢查thi s http://stackoverflow.com/questions/1085801/how-to-get-selected-value-of-dropdownlist-using-javascript – PresleyDias 2012-04-02 12:06:04

回答

4

使用以下命令行:

document.getElementById('select_value').value ="val3"; 

or 

    document.getElementById('select_value').selectedIndex = 3; 

希望這能解決問題烏爾。

+0

謝謝,第一個選項似乎已經完成了這個把戲:) – Kim 2012-04-02 12:09:52

+0

以及代碼替換選定的值它不檢索它,所以問題是錯誤的 – 2012-04-02 12:13:08

0

用普通的JavaScript:

var element = document.getElementById("select_value"); 
var selectedValue = element.options[element.selectedIndex].value; 
0

嘗試:

var mySelect = document.getElementById('select_value'); 
mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected'); 

其中index代表您要選擇的選項的位置。

0

試試這樣說:

document.getElementById('select_value').option[3].selected;

0

如果你想設置選定一個由值,試試這個功能,這將選擇VAL 3

document.getElementById('select_value').selectedIndex=3; 
0

。通過聲明一個函數,你將能夠使用這個功能與任何選擇:)。

//最簡單的版本

function setSelected(select_id,value){ 

    document.getElementById(select_id).value = value; 

} 

//或者,複雜的版本

function setSelected(select_id,value){ 

    var mySelect = document.getElementById(select_id); 
    var options = mySelect.options; 
    var key; 
    for(key in options){ 

     if(options[key].value===value){ 
      options[key].setAttribute("selected",""); 
     } 
     else 
      options[key].removeAttribute("selected"); 
    } 
} 

你的情況:

setSelected("select_value","val3"); 
+0

我測試了它,它工作正常:) – 2012-04-02 12:21:42

1
$('#select_value').val('val0'); 
相關問題