Search code examples
jqueryasp.netmasking

Jquery-number remove trailing zeros after decimal


Looking for a bit of help on some jquery

I am using jquery.number.js as per blog and github for masking http://www.teamdf.com/web/196/jquery-number-format-redux

If you have a textbox masked to 4 decimal places as soon as you type say "100" the decimal and trailing zeros appear so .0000 would appear automatically

Is it possible to stop this? Or even delay this happening until you leave the textbox?

Thanks in advance


Solution

  • By inspecting the plugin, i've discover that you can simply do this :

    $('input').blur(function(){
        this.value = $.number(this.value, 2)
    });
    

    http://jsfiddle.net/65VF6/


    Edit : restrict to 4 decimals :

    In the previous code, there was a bug when rewriting a number (comma bug). here the fix :

    $('#txtbox1').blur(function(){
        this.value = $.number(this.value.replace(/,/g, ''), 4)
    });
    

    Then, to restrain decimal point, you need an other event on keyup. Like this :

    $('#txtbox1').blur(function(){
        this.value = $.number(this.value.replace(/,/g, ''), 4)
    }).keyup(function() {
        
        var foo = this.value.replace(/(\..{0,4}).*$/, '$1')
        
        var carretPos = doGetCaretPosition(this);
        
        this.value = foo;
        
        setSelectionRange(this, carretPos, carretPos)
    });
    

    This script use custome function that you can find in this fiddle.