javascript 不允许使用负值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10886313/
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
Negative values not allowed
提问by Sam Tyson
What is the best way to prevent users from entering negative values in an input text element?
防止用户在输入文本元素中输入负值的最佳方法是什么?
Currently I am checking the field value on blur, but I am hoping somebody has a better solution.
目前我正在检查模糊的字段值,但我希望有人有更好的解决方案。
$(".payment").blur(function() {
var payment = getAmount($(this).val());
if(!isNaN(payment) && amount >= 0) {
$(this)
.css("color", "black")
.val(currency(payment));
} else {
if(amount < 0) showMessage("Negative amounts are not allowed", "error");
$(this).css("color", "red");
}
});
function getAmount(strAmount) {
var amount = new String(strAmount).replace(/$/g, "").replace(/,/g, "");
return parseFloat(amount);
}
回答by ayyp
You could use jQuery's .keypress()
and prevent the default action for the - key.
Example: http://jsfiddle.net/5cgXg/
您可以使用 jQuery.keypress()
并阻止 - 键的默认操作。示例:http: //jsfiddle.net/5cgXg/
$("#target").keypress(function(event) {
if ( event.which == 45 || event.which == 189 ) {
event.preventDefault();
}
});
回答by Andrew Odri
This ought to do the trick:
这应该可以解决问题:
$(".payment").keydown(function(event) {
if (event.keyCode == 45 ) { event.preventDefault(); }
});
This will prevent the keydown event from registering when the character code for "-" (45) is detected.
这将阻止 keydown 事件在检测到“-”(45)的字符代码时注册。
回答by David says reinstate Monica
On the assumption you might not want to work with key-codes (e.which
, e.keyCode
and so on), here's one further option:
假设您可能不想使用键代码(e.which
,e.keyCode
等等),这里有一个进一步的选择:
$('#a').blur(
function(){
var v = $(this).val(),
t = parseInt(v,10),
b = isNaN(t);
if (b){
$(this).val('');
}
else {
$(this).val(Math.abs(t));
}
});?
References:
参考:
回答by sachleen
回答by Sam Tyson
Thanks for all of the answers.
感谢所有的答案。
Here is what I ended up with:
这是我最终的结果:
$("input.payment").keypress(function(e) {
validateNumeric(e);
});
function validateNumeric(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}