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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:21:21  来源:igfitidea点击:

Negative values not allowed

javascriptjquery

提问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.keyCodeand so on), here's one further option:

假设您可能不想使用键代码(e.whiche.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));
        }
    });?

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by sachleen

You can use jQuery's keypressor keydownevents to test against the input on every key.

您可以使用 jQuery 的keypresskeydown事件来测试每个键上的输入。

If you haveother fields that need validating as well, consider jQuery Validationplugin.

如果您还有其他需要验证的字段,请考虑使用 jQuery验证插件。

回答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();
   }
}