Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative values not allowed

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);
}
like image 646
Sam Tyson Avatar asked Jun 09 '26 06:06

Sam Tyson


1 Answers

You could use jQuery's .keypress() and prevent the default action for the - key. Example: http://jsfiddle.net/5cgXg/


$("#target").keypress(function(event) {
  if ( event.which == 45 || event.which == 189 ) {
      event.preventDefault();
   }
});
like image 140
ayyp Avatar answered Jun 11 '26 20:06

ayyp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!