你好,SO上好。
所以我在贷款计算器中有一个输入字段。在这里,我希望用户输入的输入值以小数格式(在示例中更容易区分100000和1000000)。
我想使用JavaScript来做这个“转换”,如果我可以这样称呼它,我在MDN Docs中发现了一个关于一个名为“Intl.NumberFormat”的对象construtctor的东西
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
我在自己的JS文件中粘贴了以下内容,如下所示:
// Changes Loan Amount input to decimal format
document.getElementById("amount").addEventListener("input", function(){
new Intl.NumberFormat('en-CA', {style: "decimal"}).format(amount);
});
我的HTML看起来像这样:
<span class="input-group-text">$</span>
<input
type="text"
class="form-control"
id="amount"
placeholder="Loan Amount"
/>
所以我正在寻找的结果是输入看起来像用户输入时是这样的:
而不是这个:
希望这很清楚。在此先感谢您的帮助。
您没有使用格式化文本更新输入字段:
document.getElementById("amount").addEventListener("input", function(){
document.getElementById("amount").value = new Intl.NumberFormat('en-CA', {style: "decimal"}).format(document.getElementById("amount").value);
});
但是,我认为你会想要从每个输入迭代中删除非数字字符,所以这可能更接近你想要的:
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(''));
});