[英]Input value formatted with decimals
你好,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(''));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.