2012-08-07 47 views
0

this thread中,描述瞭如何使用JavaScript從下拉框中獲取選定的值。我一直試圖按照該線程中的說明進行操作,但一直未能實現。無法使用JavaScript在下拉框中獲取選定的值

這是我想要做的一個最小(非工作)的例子。代碼應該從下拉框中打印第二個選項的值,但是在第11行的Chrome的JavaScript控制檯Uncaught TypeError: Cannot read property 'options' of null(即,當我定義第二個變量時)中出現以下錯誤。

<html> 
    <body> 
    <select name='a_drop_down_box'> 
     <option value='1'>One</option> 
     <option value='2' selected='selected'>Two</option> 
     <option value='3'>Three</option> 
    </select> 
    <p id='message'></p> 
    <script type="text/javascript"> 
     var test = document.getElementById("a_drop_down_box"); 
     var testValue = test.options[test.selectedIndex].value; 
     document.getElementById('message').innerHTML=testValue; 
    </script> 
    </body> 
</html> 

回答

3
document.getElementById("a_drop_down_box"); 

你有沒有注意到,你有沒有爲選擇項中定義的ID?

name屬性用於標識使用表單發送的請求的表單元素。你應該使用一個id從dom中檢索它。

或者,如果你選擇駐留在表單中,你可以這樣做:

document.getElementById("myForm").elements["a_drop_down_box"]; 
1

你忘了給您的<select>id屬性。

<html> 
    <body> 
    <select id='a_drop_down_box' name='a_drop_down_box'> 
     <option value='1'>One</option> 
     <option value='2' selected='selected'>Two</option> 
     <option value='3'>Three</option> 
    </select> 
    <p id='message'></p> 
    <script type="text/javascript"> 
     var test = document.getElementById("a_drop_down_box"); 
     var testValue = test.options[test.selectedIndex].value; 
     document.getElementById('message').innerHTML=testValue; 
    </script> 
    </body> 
</html> 
1

下拉的name屬性是「a_drop_down_box」 - 你調用它認爲這是它的id

任何時候當你得到一個'...未定義'的錯誤,它意味着你認爲你正在處理的對象(或元素,你的情況)還沒有找到。因此,在想知道爲什麼會出現錯誤之前,請始終確認此事在你的情況,你可以做:

alert(test); //undefined - no element found with that ID 
1

你忘了ID添加到您選擇的標籤

var e = document.getElementById("a_drop_down_box"); 
var strUser = e.options[e.selectedIndex].value; 

將返回2.如果你想Two,那麼這樣做:

var e = document.getElementById("a_drop_down_box"); 
var strUser = e.options[e.selectedIndex].text; 

下面是一個簡單的例子 http://jsfiddle.net/VCerV/3/

相關問題