How To Make Input Text Allowed Only Decimal And Have Specific Decimal After Comma? - Save My Knowledge
Saturday, February 4, 2017

How To Make Input Text Allowed Only Decimal And Have Specific Decimal After Comma?

Hi, this is the struggle when we have an web application that need to input decimal digit and don't want many digit after comma. I was struggling about this and I found out the way out. We just need to create input text with class "decimal-digit" like this:
<input type="text" class="decimal-digit" />
And we need to put this function on our javascript:
function bindDecimalDigit() {
    $('.decimal-digit').on('keypress',function(event){
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
       
        validateFloatKeyPress(this, event, $(this).attr("maxdigit"));
    });

    $(".decimal-digit").bind('paste', function () {
        var self = this;
        setTimeout(function () {
            var value = $(self).val().match(/[0-9.]/g).join().replace(/,/g,'');
            var desiredLength = $(self).attr("maxdigit");
            if(desiredLength == null || desiredLength == undefined)
                desiredLength = globalDigitAfterComma;
           
            number = value.split(".");
            if(number.length > 1) {
                value = number[0] + "." + number[1].substring(desiredLength, 0);
            }
            $(self).val(value);
        }, 0);
    });
}
bindDecimalDigit()
At this code, you can see that right after I create the function, I call it immediately because I want all element with class "decimal-digit" event are bind on those code.
With this code, the text will be validated every time user press a keyboard or they do "paste".

Hope this helpful 😊