0
我有一個函數,每4個數字放置一個逗號,以便格式化爲貨幣。問題是前4個數字不會在它應該添加的位置添加逗號,只有在輸入空格時纔會正確格式化所有內容。另外,爲什麼我的輸入允許空格鍵被輸入,當我把它設置爲?謝謝!JavaScript:函數沒有正確地格式化數字
<script>
//Gets the value of the key that was pressed
function keypress(e){
var z="";
var minStr = document.getElementById('min').value;
var charval = String.fromCharCode(e.keyCode);
var backspaceKey = String.fromCharCode(8);
var tabKey = String.fromCharCode(9);
var enterKey = String.fromCharCode(13);
var spaceBarKey = String.fromCharCode(32);
//Validates that only numbers and specific types of keys can be entered
if( isNaN(charval) &&
charval != backspaceKey &&
charval != tabKey &&
charval != enterKey &&
charval == spaceBarKey){
return false;
}
//Start of the function that adds commas
if(minStr.length > 1
&& charval != backspaceKey
&& charval != tabKey
&& charval != enterKey
){
//adds commas to the string
minStr = minStr.replace(/\D/g, "");
var minArray = minStr.split("");
var j = 0;
for(var i = minStr.length; i > 0; i--){
if(j == 3){
minArray.splice(i, 0, ",");
j = 0;
}
j++;
}
minArray = minArray.join("");
document.getElementById('min').value = minArray;
//Here is where it adds a comma to the first 4 numbers
if(minStr.length == 4){
var minArray = minStr.split("");
minArray.splice(1, 0, ",");
minArray = minArray.join("");
document.getElementById('min').value = minArray;
}
}
}
</script>
<body>
<input type="text" name="min" id="min" class="mini" onkeydown="return keypress(event)" placeholder="Enter the Min">
<input type="text" name="max" id="max" onkeydown="return keypress(event)" placeholder="Enter the Max">
</body>
DEMO:https://jsfiddle.net/efoc/dtqfLp05/
可以使用http://numeraljs.com/#format – Sabrina