Reputation: 525
I am using a simple number input and I have removed spinners so users can input their own number. The full input code is:
<input type="number" onkeypress="return isNumberKey(event)" id="userInputMapOne" class="form-control" min="0" step="0.01" aria-label="input value for your zone">
But I discovered a user can input larger number of decimal places than the 0.01 step required. This is annoying. On my other part of the page the step attribute works perfectly. The only difference in this particular code is I am using a bootstrap prepend forms. Otherwise there's no difference.
The input sends a value to a JavaScript function, but it would be nice if that function limited the input to two decimal places.
What code should I use for JS to not accept any decimal places more than 2 d.p?
Should I do an if > 0.99 or < 0.00 ? There must be a JS code for decimal places too, right?
Upvotes: 0
Views: 1759
Reputation: 11360
Try:
<input type="number" onkeyup="return isNumberKey(this, 2)" id="userInputMapOne" class="form-control" min="0" step="0.01" aria-label="input value for your zone">
function isNumberKey(obj, decimals) {
if (obj.value % Math.round(obj.value)) {
var divisor = Math.pow(10, decimals);
obj.value = Math.floor(obj.value * divisor)/divisor;
}
console.log(obj.value);
}
NOTE:
I used onkeyup
, which is when you want it to change.
EDIT:
If you need to also check for numbers only:
<input type="number" onkeypress="return isNumberKey(event)" onkeyup="return truncateDecimals(this, 4)" id="userInputMapOne" class="form-control" min="0" step="0.01" aria-label="input value for your zone">
function isNumberKey(evt) {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {
evt.preventDefault();
return false;
}
return true;
}
function truncateDecimals(obj, decimals) {
if (obj.value % Math.round(obj.value)) {
var divisor = Math.pow(10, decimals);
obj.value = Math.floor(obj.value * divisor)/divisor;
}
console.log(obj.value);
return true;
}
Upvotes: 1