Formatting numeric inputs with commas can make large numbers much easier to read and understand. In this guide, I’ll show you how to format numeric inputs using JavaScript to include commas for better readability.
$w("#textInput").onKeyPress((event) => {
setTimeout(() => {
formatNumberInput($w("#textInput"))
}, 10);
})
let lastInput = "";
function formatNumberInput(input) {
let inputValue = input.value;
// Remove non-numeric characters except comma
inputValue = inputValue.replace(/[^0-9,]/g, '');
// Replace commas to prepare for formatting
inputValue = inputValue.replace(/,/g, '');
// Check if input value is empty
if (inputValue === "") {
input.value = "";
lastInput[input.toString()] = "";
return;
}
// Convert the input value to a number
let numberValue = parseInt(inputValue, 10);
// Format the number with commas
let formattedValue = numberValue.toLocaleString();
// Update the input field value
input.value = formattedValue;
// Check if backspace was used
if (!lastInput) { lastInput = "" }
let backspace = lastInput.length - formattedValue.length;
if (backspace === 1) {
lastInput= formattedValue;
return;
}
lastInput = formattedValue;
}