I saw how to add commas in the thousands/millions/etc. position for users entering numbers into a text field by using the onKeyPress function from this post:
Here’s the code I referenced:
Since I will have around 20 fields on a form where I would like to perform the same action, I wanted to ask if it’s possible to have just one “parseString” function and have each field pass its value to it when onKeyPress is triggered for the active field. I’m hoping this is possible so I don’t have to write 20 separate “parseString” functions with a unique fieldname hardcoded into each one.
Hi it is possible. Sure.
But first few comments:
But your current code uses the German format (a period for thousands and a comma for decimal). If you wish to add a comma for thousands, you should use other locales for example ‘en-US’.
If you use onInput instead of onKeyPress
1. You won’t need to set timeout
2. It will support pasting a value via the mouse right-click without pressing
In order to do it for several input elements, you can do:
$w.onReady(() => {
$w('#input1, #input2, #input3').onInput(({target}) => {
$w('#' + target.id).value = parseString(target.value);
})
})
function parseString(value){
value = value.replace(/[^0-9]/g, '');
if(value.length){
value = Number(value).toLocaleString('en-US');
}
return value;
}
I really appreciate the quick reply J.D. I added a few of my fieldnames (which are text fields) in the sample below, but when I attempted to enter a number in those fields in Preview mode, as soon as I enter one digit it immediately clears the field so that it’s blank again. The only other adjustment I made to the code you posted was to remove the very last parenthesis at the bottom since it appeared that was not needed (had the red line under it and I didn’t see a remaining open parenthesis that needed to be closed).
The regex was wrong.
It should be /[^0-9]/g an not value /^[0-9]/g
P.S next time please paste the code and not a screenshot, so I’ll be able to copy it. It will save typos on my side.