-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy patheasy-number-separator.js
68 lines (56 loc) · 1.83 KB
/
easy-number-separator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function easyNumberSeparator(config) {
// Currency Separator
let commaCounter = 10;
const obj = {
selector: config.selector || ".number-separator",
separator: config.separator || ",",
decimalSeparator: config.decimalSeparator || ".",
resultInput: config.resultInput
}
function numberSeparator(num) {
for (let i = 0; i < commaCounter; i++) {
num = num.replace(obj.separator, "");
}
x = num.split(obj.decimalSeparator);
y = x[0];
z = x.length > 1 ? obj.decimalSeparator + x[1] : "";
let rgx = /(\d+)(\d{3})/;
while (rgx.test(y)) {
y = y.replace(rgx, "$1" + obj.separator + "$2");
}
commaCounter++;
if (obj.resultInput) {
const resInput = document.querySelector(obj.resultInput)
if (resInput) {
resInput.value = num.replace(obj.separator, "")
resInput.value = num.replace(obj.decimalSeparator, ".")
}
}
return y + z;
}
function listenFields() {
document.querySelectorAll(obj.selector).forEach(function (el) {
el.addEventListener("input", function (e) {
const reg = new RegExp(
`^-?\\d*[${obj.separator}${obj.decimalSeparator}]?(\\d{0,3}${obj.separator})*(\\d{3}${obj.separator})?\\d{0,3}$`
);
const key = e.data || this.value.substr(-1)
if (reg.test(key)) {
e.target.value = numberSeparator(e.target.value);
} else {
e.target.value = e.target.value.substring(0, e.target.value.length - 1);
e.preventDefault();
return false;
}
});
el.value = numberSeparator(el.value);
});
}
listenFields()
// Fire separator when every element append to page
document.addEventListener("DOMNodeInserted", function (e) {
if ((e.target).classList.contains(obj.selector.replace('.', ''))) {
listenFields()
}
});
}