不允许使用负值

Sam*_*son 2 javascript jquery

阻止用户在输入文本元素中输入负值的最佳方法是什么?

目前我正在检查模糊的字段值,但我希望有人有更好的解决方案.

$(".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);
}
Run Code Online (Sandbox Code Playgroud)

ayy*_*yyp 9

您可以使用jQuery .keypress()并阻止 - 键的默认操作.示例:http://jsfiddle.net/5cgXg/


$("#target").keypress(function(event) {
  if ( event.which == 45 || event.which == 189 ) {
      event.preventDefault();
   }
});
Run Code Online (Sandbox Code Playgroud)