事件更改值Combobox JavaScript JSP

时间:2012-02-24 04:52:37

标签: javascript javascript-events

我希望在更改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: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    
   <script>document.write(selGate)</script>
   </form>
            <script>
                function chGate()
                {
                    selGate = document.getElementsByName("cmbGate").selectorText;
                    frGate.submit();
                }
            </script>                  

2 个答案:

答案 0 :(得分:3)

你的功能看起来像这样:

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应该改变如下:

==&GT;更改选择

<SELECT id="cmbGate" STYLE ="width: 600px" SIZE = 15 onchange="chGate()">
//      ^^ set the id

==&GT;更改表格

<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/

答案 1 :(得分:0)

您的代码存在很多问题,主要是因为它遍布整个地方,其中一半不受任何事件的约束。你真正想要的是这样的:

<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中查看此内容。