[英]Cannot fetch the selected value in a drop down box using JavaScript
在該線程中 ,描述了如何使用JavaScript從下拉框中獲取選定的值。 我一直在嘗試按照該線程中的說明進行操作,但未能使其正常運行。
這是我要執行的操作的最小示例(無效)。 該代碼應從下拉框中打印第二個選項的值,但是相反,我在Chrome的JavaScript控制台中收到以下錯誤Uncaught TypeError: Cannot read property 'options' of null
第11行(即當我定義了第二個變量)。
<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>
document.getElementById("a_drop_down_box");
您是否注意到尚未為選擇項定義ID?
name
屬性用於為使用表單發送的請求標識表單元素。 您應該使用ID從dom中檢索它。
或者,如果您的選擇位於表單內,則可以使用以下方法:
document.getElementById("myForm").elements["a_drop_down_box"];
您忘記為<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>
下拉列表的name
屬性是“ a_drop_down_box”-您以它的id
name
它。
每當您收到“ ...未定義”錯誤時,就意味着找不到您認為正在使用的對象(或元素,在您的情況下)。 因此,在懷疑為什么會發生錯誤之前,請務必進行確認。 就您而言,您可以做到:
alert(test); //undefined - no element found with that ID
您忘記在選擇標簽中添加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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.