开发者

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 automatic开发者_Python百科ally occur once I am done typing and don't want to show extra any (,)s.


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);
});


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜