fix toman format js
This commit is contained in:
@@ -28,13 +28,32 @@
|
||||
document.addEventListener("input", (event) => {
|
||||
if (event.target.classList.contains("price-input")) {
|
||||
const input = event.target;
|
||||
const cursor = input.selectionStart;
|
||||
const raw = input.value.replace(/,/g, "");
|
||||
const cursorPosition = input.selectionStart;
|
||||
const oldValue = input.value;
|
||||
const raw = oldValue.replace(/,/g, "");
|
||||
const formatted = format(raw);
|
||||
|
||||
if (input.value !== formatted) {
|
||||
if (oldValue !== formatted) {
|
||||
// Count commas before cursor in old value
|
||||
const commasBeforeCursor = (oldValue.substring(0, cursorPosition).match(/,/g) || []).length;
|
||||
// Count commas before cursor position in raw value
|
||||
const rawCursorPosition = cursorPosition - commasBeforeCursor;
|
||||
|
||||
// Set the formatted value
|
||||
input.value = formatted;
|
||||
input.setSelectionRange(cursor, cursor);
|
||||
|
||||
// Calculate new cursor position
|
||||
let newCursorPosition = 0;
|
||||
let rawIndex = 0;
|
||||
|
||||
for (let i = 0; i < formatted.length && rawIndex < rawCursorPosition; i++) {
|
||||
if (formatted[i] !== ',') {
|
||||
rawIndex++;
|
||||
}
|
||||
newCursorPosition++;
|
||||
}
|
||||
|
||||
input.setSelectionRange(newCursorPosition, newCursorPosition);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user