Reputation: 71
Hello good people on SO.
So I have an input field in an Loan Calculator. In here I want the input value the user puts in to format with decimals (To more easily distinguish between 100000 and 1000000 in example.)
I want to use JavaScript to do this "conversion" if i might call it that, and I found something in the MDN Docs about a object construtctor called "Intl.NumberFormat"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
And I pasted in the following in my own JS file as shown below:
// Changes Loan Amount input to decimal format
document.getElementById("amount").addEventListener("input", function(){
new Intl.NumberFormat('en-CA', {style: "decimal"}).format(amount);
});
My HTML Looks like this:
<span class="input-group-text">$</span>
<input
type="text"
class="form-control"
id="amount"
placeholder="Loan Amount"
/>
So the results I'm looking for Is to have the input look like when a user is typing is this:
Instead of this:
Hope this was clear. Thanks in advance for any help.
Upvotes: 3
Views: 102
Reputation: 193
You're not updating the input field with the formatted text:
document.getElementById("amount").addEventListener("input", function(){
document.getElementById("amount").value = new Intl.NumberFormat('en-CA', {style: "decimal"}).format(document.getElementById("amount").value);
});
But, I think you'll want to strip non-numeric characters from each input iteration, so this might be closer to what you want:
document.getElementById("amount").addEventListener("input", function(){
document.getElementById("amount").value = new Intl.NumberFormat('en-CA', {style: "decimal"}).format(document.getElementById("amount").value.match(/\d+/g).join(''));
});
Upvotes: 1