我有一个<input type="number">,我想将用户的输入限制为纯数字或带有小数点后最多2位的数字。

基本上,我是在要求一个价格输入。

我想避免使用正则表达式。有办法吗?

<input type="number" required name="price" min="0" value="0" step="any">

当前回答

这个问题已经有答案了,但是你可以允许小数 使用step属性。 你可以在这里阅读更多关于它的内容:Allow-decimal-values

其他回答

使用step="而不是step="any",因为它允许小数位数任意。“01”,最多允许小数点后两位。

更多详细信息见规范:https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

输入:

step="any"
class="two-decimals"

脚本:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

试着在输入类型中只允许2个小数

<input type="number" step="0.01" class="form-control"  />

或者使用jQuery的建议@SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

只需添加step="。01”,整理了我的问题。

<input type="number" class="form-control" name="price" step=".01">

步骤1:将HTML数字输入框与onchange事件挂钩

myHTMLNumberInput.onchange = setTwoNumberDecimal;

或者HTML代码

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

步骤2:编写setTwoDecimalPlace方法

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

您可以通过改变传递给toFixed()方法的值来改变小数点后的位数。请参阅MDN文档。

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer