javascript - 用小数格式化的输入值
问题描述
你好,好人。
所以我在贷款计算器中有一个输入字段。在这里,我希望用户输入的输入值用小数格式化(例如,为了更容易区分 100000 和 1000000。)
如果我可以这样称呼它,我想使用 JavaScript 来进行这种“转换”,并且我在 MDN Docs 中找到了一些关于名为“Intl.NumberFormat”的对象构造函数的内容
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(''));
});
推荐阅读
- javascript - jquery验证插件没有提交按钮
- php - Cakephp 3 hasMany关联数组以正确的json格式转换
- python - Django Haystack - 未显示覆盖的 SearchForm 中字段的初始值
- android - 在回收站视图网格布局管理器中删除卡片之间的填充
- javascript - Angular 5 社交登录 idpiframe_initialization_failed AWS Cloud 9
- c - 分叉后开始
- python - Py-solc 和 Solidity 导入
- prolog - Prolog递归列表改组
- python - 当使用全局变量作为文件名时,如何保持全局变量的值?
- amazon-web-services - 如何在 Step 函数中的 lambda 函数之间传递数据?