air
air

Reputation: 6264

How to customize the Masked Input jQuery plugin

I am using the jQuery mask plugin from

http://digitalbush.com/projects/masked-input-plugin/

I want to customize my plugin and have tried my best to do it but I can't.

What I want is

  1. I can enter digits only.
  2. All the digits will be formatted automatically (,) after every 3rd number.
  3. Only two digits after (.)

I am using this mask:

$("#product").mask("999,999,999.99",{placeholder:" "});

The problem with this is if I need to type only 150.50, I need to bring my cursor on the exact place and type.

For example in the above mask if I type 150.50 the text box looks like this: [][][],[][][],150.50 where [] is a blank space. What I want is for only 150.50 to be shown, without the extra (,)s.
If I type 1150.50 then show 1,150.50, but I want the formatting to automatically occur once I am done typing and don't want to show extra any (,)s.

Upvotes: 0

Views: 3694

Answers (2)

Adam
Adam

Reputation: 1874

Gaby's answer is correct and provides far more options than mine. However, I whipped up a solution for your specific needs. View it here.

$('input').bind('keyup blur', function(){
    var i, j, final = '', input = $(this),
        raw = input.val().replace(/[^\d]/g, '');
    while (raw.substr(0, 1) === '0' && raw.length > 2) { //remove leading 0s for large numbers
        raw = raw.substr(1);
    }
    while (raw.length < 2) { //pad with up to two 0s for small numbers
        raw = '0' + raw;
    }
    for (i = 1; i <= raw.length; i++) { //format the number as ##,###,###.##
        j = raw.length - i;
        final =
            (i === 2 ? '.' : ((i + 1) % 3) === 0 && i != raw.length ? ',' : '')
            + raw.substr(j, 1)
            + final;
    }
    input.val(final);
});

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You do not want a masking plugin, but a formatting plugin ..

have a look at http://plugins.jquery.com/project/number_format

Upvotes: 1

Related Questions