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);
}
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With