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
- I can enter digits only.
- All the digits will be formatted automatically (,) after every 3rd number.
- 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.
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
精彩评论