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

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

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

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

当前回答

我对其中一些解决方案有过一段奇怪的编辑经历。从用户的角度来看,这似乎非常有效(只在必要时进行干预):

function handleNumberChanged (e) {
    const fixed = parseFloat(e.target.value).toFixed(2).toString()
    if (fixed.length < parseFloat(e.target.value).toString().length)
      e.target.value = fixed
}

其他回答

使用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();
        } 
    }
}

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

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

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

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

你可以用这个。反应钩子

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

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

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

或者使用jQuery的建议@SamohtVII

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