The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString()
. For that reason I added the toNumber()
function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e)
and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e)
and format it back to a number.
This makes sure you won't get NaN
when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN
as text cannot be formatted to a number. This could be filtered out in the toString(e)
when necessary. I did this in the example below by adding if (formatted !== 'NaN') {}
Only when it's not NaN
it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e)
does it's thing and filter the dots, text etc. so only the numbers remain.