[英]Step not working for an input in HTML - the field is accepting any number of decimal places
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.但我发现用户可以输入比所需的 0.01 步长更多的小数位数。 This is annoying.
这很烦人。 On my other part of the page the step attribute works perfectly.
在我页面的另一部分, step 属性完美运行。 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.输入向 JavaScript 函数发送一个值,但如果该函数将输入限制为两位小数,那就太好了。
What code should I use for JS to not accept any decimal places more than 2 dp?我应该使用什么代码让 JS 不接受任何超过 2 dp 的小数位?
Should I do an if > 0.99 or < 0.00 ?我应该做 if > 0.99 还是 < 0.00 ? There must be a JS code for decimal places too, right?
小数点也一定有JS代码吧?
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.我使用了
onkeyup
,这是你想要改变的时候。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.