Reputation: 65
I'm trying to validate user input data using jquery. Here is the code I use.
$('#ole').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
The code above allows only integers and a single dot. What I need is to allow only two integers after the dot.
How to achieve that ?
Upvotes: 0
Views: 894
Reputation: 7452
Use a Regex expression and round the decimals:
$('#ole').on('blur', function()
{
var val = $(this).val();
if (val.match(/^\d+\.{0,1}\d+$/))
{
// Convert to int if needed
val = parseInt(val);
val = Math.round(val *100)/100; // Round to 2 decimals
$(this).val(val);
}
});
Upvotes: 1
Reputation: 54016
TRY with this
<input id="ole" class="decimal">
$(document).on('change blur','.decimal',function() {
var amt = parseFloat(this.value);
if(isNaN(amt)) {
$(this).val('');
}
else {
$(this).val(amt.toFixed(2));
}
});
Upvotes: 3