| 1 |
www |
1 |
(function($){
|
|
|
2 |
$.fn.extend({
|
|
|
3 |
inputNumberFormat: function(options) {
|
|
|
4 |
this.defaultOptions = {
|
|
|
5 |
'decimal': 2,
|
|
|
6 |
'decimalAuto': 2,
|
|
|
7 |
'separator': '.',
|
|
|
8 |
'separatorAuthorized': ['.', ',']
|
|
|
9 |
};
|
|
|
10 |
|
|
|
11 |
var settings = $.extend({}, this.defaultOptions, options);
|
|
|
12 |
|
|
|
13 |
var matchValue = function(value, options) {
|
|
|
14 |
var regexp = "^[0-9]+";
|
|
|
15 |
|
|
|
16 |
if(options.decimal) {
|
|
|
17 |
regexp += "["+options.separatorAuthorized.join("")+"]?[0-9]{0," + options.decimal + "}";
|
|
|
18 |
}
|
|
|
19 |
|
|
|
20 |
regexp = new RegExp(regexp + "$");
|
|
|
21 |
|
|
|
22 |
return value.match(regexp);
|
|
|
23 |
}
|
|
|
24 |
|
|
|
25 |
var formatValue = function(value, options) {
|
|
|
26 |
var formatedValue = value;
|
|
|
27 |
|
|
|
28 |
if(!formatedValue) {
|
|
|
29 |
return formatedValue;
|
|
|
30 |
}
|
|
|
31 |
|
|
|
32 |
formatedValue = formatedValue.replace(",", options.separator);
|
|
|
33 |
|
|
|
34 |
if(options.decimal && options.decimalAuto) {
|
|
|
35 |
|
|
|
36 |
formatedValue = Math.round(formatedValue*Math.pow(10,options.decimal))/(Math.pow(10,options.decimal))+"";
|
|
|
37 |
|
|
|
38 |
if(formatedValue.indexOf(options.separator) === -1) {
|
|
|
39 |
formatedValue += options.separator;
|
|
|
40 |
}
|
|
|
41 |
|
|
|
42 |
var nbDecimalToAdd = options.decimalAuto - formatedValue.split(options.separator)[1].length;
|
|
|
43 |
for(var i=1; i <= nbDecimalToAdd; i++) {
|
|
|
44 |
formatedValue += "0";
|
|
|
45 |
}
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
return formatedValue;
|
|
|
49 |
}
|
|
|
50 |
|
|
|
51 |
return this.each(function() {
|
|
|
52 |
var $this = $(this);
|
|
|
53 |
|
|
|
54 |
$this.on('keypress', function(e) {
|
|
|
55 |
if(e.ctrlKey) {
|
|
|
56 |
|
|
|
57 |
return;
|
|
|
58 |
}
|
|
|
59 |
|
|
|
60 |
if(e.key.length > 1) {
|
|
|
61 |
|
|
|
62 |
return;
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
var options = $.extend({}, settings, $(this).data());
|
|
|
66 |
|
|
|
67 |
var beginVal = $(this).val().substr(0, e.target.selectionStart);
|
|
|
68 |
var endVal = $(this).val().substr(e.target.selectionEnd, $(this).val().length - 1);
|
|
|
69 |
var val = beginVal + e.key + endVal;
|
|
|
70 |
|
|
|
71 |
if(!matchValue(val, options)) {
|
|
|
72 |
|
|
|
73 |
e.preventDefault();
|
|
|
74 |
return;
|
|
|
75 |
}
|
|
|
76 |
|
|
|
77 |
});
|
|
|
78 |
|
|
|
79 |
$this.on('blur', function(e) {
|
|
|
80 |
var options = $.extend({}, settings, $(this).data());
|
|
|
81 |
|
|
|
82 |
$(this).val(formatValue($(this).val(), options));
|
|
|
83 |
});
|
|
|
84 |
|
|
|
85 |
$this.on('change', function(e) {
|
|
|
86 |
var options = $.extend({}, settings, $(this).data());
|
|
|
87 |
|
|
|
88 |
$(this).val(formatValue($(this).val(), options));
|
|
|
89 |
});
|
|
|
90 |
});
|
|
|
91 |
}
|
|
|
92 |
});
|
|
|
93 |
})(jQuery);
|