添加选项时<opt>进行更新</select>

时间:2010-08-02 02:17:26

标签: javascript html

我有一个看似这样的SELECT。

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

在某个时刻,我的javascript将OPTION设置如下:

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

问题是您必须单击选择它才能显示myText。如何在运行该javascript后立即显示myText(带myValue)?

4 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

使用body标签的onLoad属性加载脚本? e.g。

<body onload="initSelect()">

或者只是将脚本放在select标签之后:

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

答案 2 :(得分: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

答案 3 :(得分:0)

问题是我使用的jQuery插件(Uniform),我没有意识到我必须运行$ .uniform.update()

http://pixelmatrixdesign.com/uniform/