-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (62 loc) · 1.92 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
function cents(value) {
let cents = value.replace(/[$,]/g, '')
return cents * 100
}
function format(value, options = {}) {
if (typeof options !== 'object') {
throw new Error(
`[format-dollars] Options must be an object but a ${typeof options} was passed as the second argument instead.`
)
}
let formattedValue = value.toString()
formattedValue = formattedValue.replace(/[^\d.-]/g, '')
formattedValue = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(formattedValue.replace(/[^0-9.]/g, ''))
if (formattedValue === '$NaN') {
formattedValue = '$0.00'
}
if (options.removeCents) {
formattedValue = formattedValue.replace(/[^.]+$/, '')
formattedValue = formattedValue.substr(0, formattedValue.length - 1)
}
if (options.removeSymbol) {
formattedValue = formattedValue.replace(/[$,]/g, '')
}
if (options.removeCommas) {
formattedValue = formattedValue.replace(/[,]/g, '')
}
return formattedValue
}
function watch(elementSelector, options = {}) {
if (typeof options !== 'object') {
throw new Error(
`[format-dollars] Options must be an object but a ${typeof options} was passed as the second argument instead.`
)
}
const elements = document.querySelectorAll(elementSelector)
for (let el of elements) {
if (el.type !== 'text' && el.type !== 'number') {
throw new Error(
`[format-dollars] Your input type must be "text" or "number" but is currently "${el.type}".`
)
}
if (el.type === 'number') {
options.removeSymbol = true
}
el.addEventListener('blur', (event) => {
const formattedValue = format(event.target.value, options)
event.target.value = formattedValue
if (!options.removeDataCentsAttribute) {
el.dataset.cents = cents(formattedValue)
}
})
}
}
const formatCurrencyInput = {
watch,
format,
cents,
}
module.exports = formatCurrencyInput