I need to add a thousands separator while the user is typing. I have an observer function that watches a property which is bind to the input so every time the user types in the input I get two values, newValue and oldValue.
E.g.: The user wants to type '12600' which should be displayed as '12.600'.
Until that part, my code is working.
When I went to test it, I realized that my function doesn't work properly because when I delete a single digit it won't delete it.
E.g.: '12.600' -> '1.260' wont work.
At the end of my function, I assign the new value to my property which is bind to the input value so it triggers another change and my function is executed again, which sets my property's value to the old one.
_turnoverObserver: function (newValue, oldValue) {
let result = [];
if (newValue !== undefined && newValue !== null) {
//this.turnover = String(newValue).split('.').join('').split("").reverse().join("").match(/.{1,3}/g).join(".").split("").reverse().join("");
//this.turnover = Number(this.turnover).toLocaleString();
if (newValue.length > 3) {
let withoutCommasStr = newValue.split('.').join('');
let withoutComasArr = withoutCommasStr.split('');
let reversedArr = withoutComasArr.reverse();
reversedArr.forEach((num, index) => {
if (index !== 0 && index % 3 === 0) {
result.push('.');
}
result.push(num);
});
let finalArr = result.reverse();
this.turnover = finalArr.join('');
}
}
}
Say the I want to type '1260'.
1) 1
2) 12
3) 126
4) 1.620
But when I delete any number it will execute my function again but won't delete it...
1) '1.260'
2) Press delete
3) Still '1.260'
You can try this jquery
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>