我使用JavaScript创建了一个简单的下拉菜单,其中显示了一年中的某个月。每个选项都有一个值。使用onchange
函数调用另一个函数count
时,我无法读取下拉菜单的值。
功能count
:
<script language="javascript" type="text/javascript">
function count(){
debugger;
alert(lst_MonthDrop.value);
}
</script>
下拉菜单:
<select name="lst_MonthDrop"
style="background-color:#FF9933; color:#FFF; border:none; border-radius:5px;"
onchange="count()">
<option> When do you want to go?</option>
<option value="2014-01-01">January</option>
<option value="2014-02-01">Feburary</option>
<option value="2014-03-01">March</option>
<option value="2014-04-01">April</option>
<option value="2014-05-01">May</option>
<option value="2014-06-01">June</option>
<option value="2014-07-01">July</option>
<option value="2014-08-01">August</option>
<option value="2014-09-01">September</option>
<option value="2014-10-01">October</option>
<option value="2014-11-01">November</option>
<option value="2014-13-01">December</option>
</select>
答案 0 :(得分:0)
选择一个ID:<select name="lst_MonthDrop" id="first-month">
,然后使用此功能重试:
function count(){
var firstMonth = document.getElementById('first-month');
// Value of the selected option
alert(firstMonth.value);
// Text of the selected option
alert(firstMonth.options[firstMonth.selectedIndex].text);
}
答案 1 :(得分:0)
选择一个ID并检索如下内容:
var lst_MonthDrop = document.getElementById('lst_MonthDrop');
alert(lst_MonthDrop.options[lst_MonthDrop.options.selectedIndex].innerHTML);
答案 2 :(得分:0)
修改onchange
以致电count(this)
<select name="lst_MonthDrop" style="background-color:#FF9933; color:#FFF; border:none; border-radius:5px;" onchange="count(this)">
<option> When do you want to go?</option>
<option value="2014-01-01">January</option>
<option value="2014-02-01">Feburary</option>
<option value="2014-03-01">March</option>
<option value="2014-04-01">April</option>
<option value="2014-05-01">May</option>
<option value="2014-06-01">June</option>
<option value="2014-07-01">July</option>
<option value="2014-08-01">August</option>
<option value="2014-09-01">September</option>
<option value="2014-10-01">October</option>
<option value="2014-11-01">November</option>
<option value="2014-13-01">December</option>
</select>
然后给count函数一个参数:
function count(s){
alert(s.value);
}
当调用onchange
事件时,它会传递对select
元素的引用,然后您可以从该引用中获取值。