简体   繁体   English

javascript从下拉列表中获取价值

[英]javascript get value from dropdown

I have a php script with an array which loops through months and displays them in a drop down. 我有一个带有数组的php脚本,它可以循环几个月,并在下拉列表中显示它们。 I want to get the selected value from the drop down using javascript. 我想使用javascript从下拉列表中获取选定的值。

function month_list()
{


 $months = Array("January", "February", "March", "April", "May", "June", "July", 
 "August", "September", "October", "November", "December");

 echo '<select name="month" id="month_list" OnChange="getvalue();">'; 

 foreach ($months as $months => $month)
 {
         echo'<option OnChange="getvalue();" value='.$month.'>'.$month.'</option>';

     }

 echo '</select>';

}

Javascript: 使用Javascript:

 <script type="text/javascript">


 function getvalue()
 {
 alert(document.getElementById((month_list)).value); 
 }

</script>

Nothing happends when I select a value but in firebug I get the error: 当我选择一个值时什么也没发生,但是在萤火虫中我得到了错误:

Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.

Any advice? 有什么建议?

Thanks. 谢谢。

You forgot to quote month_list. 您忘记了引用month_list。

 document.getElementById("month_list").value

Also you don't need the onchange (that's all lowercase btw) attributes on the individual options, just on the select element. 另外,您不需要单个选项上的onchange(全部为小写btw)属性,而仅在select元素上。

Use 采用

function getvalue()
{
alert(document.getElementById('month_list').value); 
}

</script>

Instead. 代替。

Also, you can remove the onChange on each of the options, the select will do :) 另外,您可以删除每个选项的onChange,选择将起作用:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM