This is an easy way to make price inputs or other float inputs validate and readable.
- The script operates on the inputs with class .priceBox.
- The script is triggered on ‘keyup’ while you write.
- Adds dots on thousands,millions etc.
- Does not allow more than 2 decimal digits
- Removes non numeric characters.
- Holds value in data-float. You can get it with
.data('float')
. - Changes the input that operates on.
- Works with jquery and also with zepto.js
example
Input | Output | Description |
---|---|---|
1234567,89 | 1.234.567,89 | Adds dots. |
12345,6789 | 12.345,67 | Only 2 decimals digits. |
abc1234,d567 | 1.234,56 | Removes non numeric |
options
options | var | type | description |
---|---|---|---|
Separator | s | char | Character to separate thousands, millions etc. |
Decimal Separator | d | char | Character to separate decimal and integer part. |
Decima Digits | dd | int | Maximum decimal digits. |
script
$('input.priceBox').on('priceIt',function(e){
var d=',',
s='.',
dd=2,
v=$(this).val().replace(s,'').split(d),
l=v.length;
for(var i=0;i<l;i++)
{
v[i]=v[i].replace(/\D/g,'',10);
}
if(l>1)
{
v[l-1]=d+v[l-1].substr(0,dd);
}
v=v.join('');
if(v.lastIndexOf(d)==0)
{
v="0"+v;
}
$(this).data('float',v.replace(d,s)).val(v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+s));
}).on('keyup',function(e){
$(this).trigger('priceIt');
});
Sample
Create an input element with class .priceBox include this script and jquery or zepto.js.