Hi, I'm pretty new to js. I could use some help with this one. I'm loading a <input type="number"> element which will load a currency from the backend, but I need to create some kind of javascript function that will dynamically format the integer into a currency even when the user edits the number. For example, the page loads and the backend sends 1000.02 as the value for the element. It should display as 1,000.02 with commas and decimals in the right places. If the users decides to edit the number and change it to 1000000.02 than it should automatically add the comma as they type. I'm not sure how to call this function or how to use such a function. I was thinking of doing something like this
<?php
$data = new DataGetter;
?>
<input type="number" onChange="currencyConverter(this)" value="<?= $data->getData(); ?>">
<script>
function currencyConverter(element){
let input = element.value;
let format = new Intl.NumberFormat("en-US", {
style: 'currency',
currency: 'USD'
}).format(input);
return format;
}
</script>
@personalhomepage Don’t do this with number inputs. It will just lead to bugs.
By all means, format prices when displaying them as text. But present numbers as numbers for formatting; not formatted strings. It will also only confuse users as they won’t know if they’re supposed to add commas, why commas are disappearing if they edit values, etc. So it just leads to poor UX.
@martinbean that's a good point. Plus I already had it formatted in php as comma separated, but I was worried users would get upset that it doesn't auto format as they type.