[英]Input value formatted with decimals
Hello good people on SO. 你好,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.)
在这里,我希望用户输入的输入值以小数格式(在示例中更容易区分100000和1000000)。
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" 我想使用JavaScript来做这个“转换”,如果我可以这样称呼它,我在MDN Docs中发现了一个关于一个名为“Intl.NumberFormat”的对象construtctor的东西
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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: 我在自己的JS文件中粘贴了以下内容,如下所示:
// 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: 我的HTML看起来像这样:
<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.
在此先感谢您的帮助。
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(''));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.