从 <select> onchange 调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12541923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling javascript function from <select> onchange
提问by Saaram
I am trying to call a javascript function from the onchange attribute of the select
tag ! My issue is that I am passing the name attribute of the select to the function which always go null.
我正在尝试从select
标签的 onchange 属性调用 javascript 函数!我的问题是我将 select 的 name 属性传递给始终为 null 的函数。
<body>
<form action="" method="post">
<select name="slct" id="name" onchange="rohan('measurement_conversion', '<?php echo isset($_POST["slct"])?$_POST["slct"]:"null" ?>')">
<option value="yes" selected="selected"> yes </option>
<option value="nopes"> nopes </option>
<option value="may be"> May be </option>
<option value="dont know"> dont know </option>
</select>
</form>
<div id="abc">
</div>
</body>
And here my javascript function
这里是我的 javascript 函数
<script>
function rohan(var1, var2)
{
document.getElementById("abc").innerHTML=var1 + " " + var2;
}
</script>
It always prints null.. Any help will be appreciated !
它总是打印 null .. 任何帮助将不胜感激!
回答by Raj Adroit
HTML:
HTML:
<body>
<form action="" method="post">
<select name="slct" id="name" onchange="rohan(this.value)">
<option>Select</option>
<option value="yes" selected="selected"> yes </option>
<option value="nopes"> nopes </option>
<option value="may be"> May be </option>
<option value="dont know"> dont know </option>
</select>
</form>
</body>
JS:
JS:
<script>
function rohan(value)
{
//you can get the value from arguments itself
alert(value);
}
</script>
回答by Sergio Laime
No put in tag HTML attribute javascript, onchange
is better in the script:
没有放入标签 HTML 属性 javascript,onchange
在脚本中更好:
<script>
var b=document.getElementById('name');
b.onchange=function (){
var a=document.getElementById('name').value;
console.log(a);
}
</script>
回答by Amber
PHP is run on the server before JavaScript is ever run in the browser. It doesn't get re-evaluated when the user changes the selected item.
在浏览器中运行 JavaScript 之前,PHP 在服务器上运行。当用户更改所选项目时,它不会被重新评估。