Javascript - onblur 函数无法更改文本框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12346407/
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
Javascript - onblur function cannot change the value of the textbox
提问by Tepken Vannkorn
I have some textboxes allowing users to enter numbers from 0 to 20. So that I have a js validation code to test if they follow the rule or not.
我有一些文本框允许用户输入从 0 到 20 的数字。这样我就有了一个 js 验证代码来测试他们是否遵守规则。
I have such the following textboxes:
我有以下文本框:
<input type="textbox" name="tx1" onblur="checkValue(this.value)" />
<input type="textbox" name="tx2" onblur="checkValue(this.value)" />
....
Then I write a js function like this:
然后我写了一个这样的js函数:
function checkValue(value) {
if (value > 20) {
return this.value = 20;
} else if (value < 0){
return this.value = 0;
} else if (value == '' || isNan(value)) {
return this.value = 0;
} else {
return this.value;
}
}
I tried to test via console.log(). I tried alert('hi') and it works. However, it does not change value at all when meeting the above conditions. So could anyone help me to solve this?
我试图通过 console.log() 进行测试。我试过 alert('hi') 并且它有效。但是,当满足上述条件时,它根本不会改变值。那么有人可以帮我解决这个问题吗?
回答by yogi
Try this
尝试这个
<input type="textbox" name="tx1" onblur="checkValue(this)" />
function checkValue(sender) {
var value = parseInt(sender.value);
if (value > 20) {
sender.value = 20;
} else if (value < 0){
sender.value = 0;
} else if (value == '' || isNan(value)) {
sender.value = 0;
} else {
return sender.value;
}
}
回答by Raab
Re-Write your code as below. Only passing this
can do the job then.
重新编写您的代码,如下所示。只有通过this
才能完成这项工作。
HTML
HTML
<input type="textbox" name="tx1" onblur="checkValue(this)" />
<input type="textbox" name="tx2" onblur="checkValue(this)" />
....
Javascript
Javascript
function checkValue(obj) {
if (obj.value > 20) {
obj.value = 20;
} else if (obj.value < 0){
obj.value = 0;
} else if (value == '' || isNan(obj.value)) {
obj.value = 0;
}
}
回答by Bathakarai
Your script is return the value but no place you to set those values. So when the blur function invokes script surely invoked.. but the value is not set any where.
您的脚本是返回值,但没有地方可以设置这些值。因此,当模糊函数调用脚本时,肯定会调用......但该值未在任何地方设置。
回答by Krishna Kumar
"isNan()" is not a function but "isNaN()" is, send input elemment, not only element's value, for update the input value.
"isNan()" 不是函数,但 "isNaN()" 是,发送输入元素,不仅是元素的值,用于更新输入值。
<script>
function checkValue(input) {
console.log(input.value);
if (input.value > 20) {
return input.value = 20;
} else if (input.value < 0){
return input.value = 0;
} else if (input.value == '' || isNaN(input.value)) {
return input.value = 0;
} else {
return input.value;
}
}
</script>
<input type="textbox" name="tx1" onblur="checkValue(this)" />
<input type="textbox" name="tx2" onblur="checkValue(this)" />