HTML 输入文本框 onChange 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17660930/
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
HTML input textbox onChange not working
提问by fpele
This is what I have:
这就是我所拥有的:
<script language="JavaScript">
function toggle() {
if (this.value=='1') {
document.getElementById('dbOn').style.visibility='visible';
}
else {
document.getElementById('dbOn').style.visibility='hidden';
document.getElementById('dbOff').checked='checked';
}
}
</script>
<form action="index" method="post">
<input type="text" name="iterations" value="1" onChange="toggle()" >
<input type="radio" name="db" value="OFF" checked="checked" id="dbOff" >OFF<br>
<input type="radio" name="db" value="ON" id="dbOn" >ON
</form>
The idea is that you will only be allowed to write to the database if you are doing one iteration. Otherwise, I want the "ON" option to become disabled or disappear and for OFF to be checked automatically.
这个想法是,如果您进行一次迭代,您将只被允许写入数据库。否则,我希望“ON”选项被禁用或消失,并自动检查 OFF。
So far, I have tried onChange, onKeyUp and onKeyPress, but none of them appear to work. Any idea what is wrong with my code?
到目前为止,我已经尝试过 onChange、onKeyUp 和 onKeyPress,但它们似乎都不起作用。知道我的代码有什么问题吗?
Thanks
谢谢
回答by Diodeus - James MacFarlane
You need to pass a reference to your element when calling the function.
调用函数时,您需要传递对元素的引用。
onchange="toggle(this)"
You'll also need a variable for the value in your function:
您还需要为函数中的值设置一个变量:
function toggle(element) {
if (element.value=='1') {
...
}