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

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

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

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

当前回答

使用这段代码

<input type="number" step="0.01" name="amount" placeholder="0.00">

HTML5 Input元素的默认Step值为Step ="1"。

其他回答

步骤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

使用这段代码

<input type="number" step="0.01" name="amount" placeholder="0.00">

HTML5 Input元素的默认Step值为Step ="1"。

使用Javascript在文本框中只输入3个小数点。

<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>

function AllowOnlyAmountAndDot(id, e, decimalbool) {    
    if(decimalbool == true) {   
        var t = id.value;
        var arr = t.split(".");
        var lastVal = arr.pop();
        var arr2 = lastVal.split('');
        if (arr2.length > '2') {
            e.preventDefault();
        } 
    }
}

你可以用这个。反应钩子

输入< 类型=“当家” name = "价格" 普莱斯placeholder =“回车” 一步=“任何” 所需 />

  <input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">

  var validate = function(e) {
      var t = e.value;
      e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
  }