Reading Time: < 1 minute
Hello there, this time I'd like to explain how to limit two decimal digits in a jQuery input field. This is how to do it:
HTML code
<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">
Javascript code
// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this; //for chaining
});
});
A tool for creating sample code
Here's an useful tool to create sample code suitable for our needs.
In Haml and CoffeeScript
Haml code
%input#other_amount.numeric{type: 'text', name: 'other_amount'}
Coffescript code:
//Use this function to validate an input to limit with 2 decilmals after decimal point
$.fn.twoDigits = ->
unless $(this).val().indexOf(".") is -1
if $(this).val().split(".")[1].length > 2
return if isNaN(parseFloat(this.val()))
result = parseFloat(this.val()).toFixed(2)
this.val result
result
How to summon from our view
$('#other_amount').twoDigits()
Hope you found this guide useful. Shoot me up any comments you may have. Thank you for visiting our blog!
H.