2010-08-02 10 views
0

我有一個SELECT,看起來像這樣。獲取<select>當您添加選項時更新

<select id="mySelect"><option value="">Please select</option></select> 

在某一點上,我的javascript設置選項,如下所示:

var elSel = document.getElementById('mySelect'); 
elSel.options[0].value = myValue; 
elSel.options[0].text = myText; 

的問題是,你必須點擊選擇爲它會將myText展示。我該如何讓myText(使用myValue)在我運行該javascript後立即顯示?

+0

該JS在哪裏/如何執行? – NullUserException 2010-08-02 02:21:59

+0

JS正在執行時,他們點擊一個按鈕 – babonk 2010-08-02 02:24:19

回答

0

使用body標籤的onLoad屬性加載腳本?例如

<body onload="initSelect()"> 

或者乾脆把劇本選擇標籤後:

<select>...</select> 
<script>//code to generate the options</script> 
+0

問題是,JS正在執行時,他們點擊一個按鈕。所以它不會發生onload,它不可能總是像第二個例子那樣發生。對不起,以前沒有指定。 – babonk 2010-08-02 02:23:50

1

添加elSel.selectedIndex = 0;到腳本的結尾。如果您打算有超過1個項目並且您想要選擇最後一個項目,請使用elSel.options.length-1

<html> 
<head> 
<script language="javascript"> 
function addItem() { 
var elSel = document.getElementById('test'); 
elSel.options[0].value = '1'; 
elSel.options[0].text = 'new value'; 
elSel.selectedIndex = 0; 
} 
</script> 
</head> 
<body> 
<form> 
<select id="test"><option value="1">- SELECT AN ITEM -</option></select> 
<input type="button" value="Add Item" onclick="addItem();" /> 
</form> 
</body> 
</html> 
+0

試過了,沒有奏效。 (使用Firefox 3.0.11) – babonk 2010-08-02 02:25:09

+0

實際上,它工作得很好。我已經發布了整個代碼示例供您嘗試,並在Chrome和最新版本的Firefox中進行了測試。 – Tahbaza 2010-08-02 02:35:27

+0

有趣,它不適合我。我應該補充的是,在添加元素之前,它被禁用(因爲css)。 但是,我發現在選項添加代碼之前將.disabled = false與之後沒有區別。 – babonk 2010-08-02 02:46:05

0

嘗試使用DOM操作:

<select id="mySelect"> 
<option value="">Please select</option> 
</select> 
<script> 

var elSel = document.getElementById('mySelect'); 

var opt = {}; 


opt = document.createElement('option'); 
opt.value = '1'; 
opt.text = 'a'; 
elSel.appendChild(opt); 

opt = document.createElement('option'); 
opt.value = '2'; 
opt.text = 'b'; 
opt.selected = true;  /* Here is where we update the select element */ 
elSel.appendChild(opt); 

opt = document.createElement('option'); 
opt.value = '3'; 
opt.text = 'c'; 
elSel.appendChild(opt); 

</script> 

測試在這裏:

http://dl.dropbox.com/u/186012/demos/stackoverflow/select/index.html

相關問題