2012-02-24 128 views
1

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

你是什麼意思'改變javascript的價值?你能描述一下什麼是不工作的嗎? – gideon 2012-02-24 04:55:07

+0

'我想改變JavaScript的書面價值',寫入文檔的JavaScript變量這一個: 'document.write(selGate)' – Nore 2012-02-24 04:57:58

+0

它並沒有改變 – Nore 2012-02-24 04:58:44

回答

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應該改變這樣的:

==>更改選擇

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

+0

它的工作沒有'frGate.submit()' , 謝謝! :) – Nore 2012-02-24 05:14:47

+0

不客氣:)你是什麼意思?我在演示中評論了'frGate.submit()',所以它不提交頁面。 – gideon 2012-02-24 05:17:29

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

相關問題