Input value formatted with decimals

问题: 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 distingui...

问题:

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:

Wanted_Results

Instead of this:

enter image description here

Hope this was clear. Thanks in advance for any help.


回答1:

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));
});
  • 发表于 2019-03-14 23:00
  • 阅读 ( 187 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除