I am trying to make a loan calculator that only allows a maximum of two decimals to be typed at once. Unfortunately, to do this I have had to add a script for the input which disallows commas to be inputted. I am not sure why this does not allow commas. I would like commas for the purpose of separating every third number. For example, 1,000,000.
A working example of my page can be seen at: http://thetotempole.ca/sales/loancalculator.php
I am not looking for suggestions, but full solutions to my problem, please.
Here is the script I am using currently:
<script>
function trimDP(x, dp) {
x = parseFloat(x);
if (dp === 0)
return Math.floor(x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((x) * dp) / dp).toString();
}
window.addEventListener('load', function () {
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
});
</script>
and here is my input code:
<input type=text name=loan size=10 class="dp2">