事件更改值组合框JavaScript JSP
问题描述:
我想在更改ComboBox的值后更改JavaScript的书面值。但它没有工作,这里是我的代码:事件更改值组合框JavaScript JSP
<script>var selGate = "empty"</script>
<SELECT NAME = "cmbGate" STYLE ="width: 600px" SIZE = 15 onchange="chGate()">
<OPTION Value = "opt1">Option 1</OPTION>
<OPTION Value = "opt2">Option 2</OPTION>
</SELECT>
<BR>
<form name="frGate">
Selected Gate is:
<script>document.write(selGate)</script>
</form>
<script>
function chGate()
{
selGate = document.getElementsByName("cmbGate").selectorText;
frGate.submit();
}
</script>
答
你函数看起来是这样的:
function chGate()
{
var e = document.getElementById("cmbGate");//get the combobox
var selGate = e.options[e.selectedIndex].value;//get selected value
//you can also do use ^.text =>to get the text instead
document.getElementById("selected").innerHTML = "Selected Gate is:"+selGate;
//^^ set the text to the selected value
frGate.submit();
}
你的HTML应该改变这样的:
==>更改选择
<SELECT id="cmbGate" STYLE ="width: 600px" SIZE = 15 onchange="chGate()">
// ^^ set the id
==>更改形式
<form name="frGate">
<div id="selected">Selected Gate is:</div>
// ^^ set an id here also so you can update it
</form>
看到一个工作演示: http://jsfiddle.net/Mr2CF/2/
答
有很多的问题,你的代码,主要是由于这样的事实,这是所有的地方,一半是未绑定到任何事件。你真正想要的是这样的:
<script type="text/javascript">
var selGate = 'empty';
document.getElementById('cmbGate').onchange = function() {
selGate = this.options[this.selectedIndex].text
document.getElementById('selectedGate').innerHTML = selGate;
}
</script>
<select id="cmbGate" name="cmbGate" style="width: 600px" size="15">
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>
<br>
<form name="frGate" id="frGate">
<p>Selected gate is: <span id="selectedGate"></span></p>
</form>
看到这个在行动here。
你是什么意思'改变javascript的价值?你能描述一下什么是不工作的吗? – gideon 2012-02-24 04:55:07
'我想改变JavaScript的书面价值',写入文档的JavaScript变量这一个: 'document.write(selGate)' – Nore 2012-02-24 04:57:58
它并没有改变 – Nore 2012-02-24 04:58:44