事件更改值组合框 JavaScript JSP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9425585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Event Change Value Combobox JavaScript JSP
提问by Nore
I want to change written value of JavaScript after i change the value of ComboBox. But it didn't work, here is my code :
我想在更改 ComboBox 的值后更改 JavaScript 的写入值。但它没有用,这是我的代码:
<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>
回答by gideon
You function would look like this:
你的函数看起来像这样:
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();
}
You html should change like this:
你的 html 应该像这样改变:
==> Change the select
==> 更改选择
<SELECT id="cmbGate" STYLE ="width: 600px" SIZE = 15 onchange="chGate()">
// ^^ set the id
==> Change the form
==> 改变形式
<form name="frGate">
<div id="selected">Selected Gate is:</div>
// ^^ set an id here also so you can update it
</form>
See a working demo: http://jsfiddle.net/Mr2CF/2/
查看工作演示:http: //jsfiddle.net/Mr2CF/2/
回答by Josh Leitzel
There are a lot of problems with your code, mostly due to the fact that it's all over the place and half of it isn't bound to any event. What you really want is something like this:
你的代码有很多问题,主要是因为它到处都是,其中一半不受任何事件的约束。你真正想要的是这样的:
<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>
See this in action here.
在此处查看此操作。