I am currently facing an issue with a function I have created to format numbers for currency by inserting commas every 4 digits. The problem lies in the fact that the first 4 numbers do not have a comma added where it should be, and the formatting only works when a space is entered. Furthermore, I am puzzled as to why my input field allows the spacebar to be entered even though I have restricted it. Any insights on these issues would be greatly appreciated. Thank you!
<script>
// Function to process key press events
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);
// Validation to only allow certain key entries
if( isNaN(charval) &&
charval != backspaceKey &&
charval != tabKey &&
charval != enterKey &&
charval == spaceBarKey){
return false;
}
// Adding commas every 4 digits
if(minStr.length > 1
&& charval != backspaceKey
&& charval != tabKey
&& charval != enterKey
){
// Adding 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;
// Adding a comma to the first 4 digits
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>