maxlength属性对<input type="number">不起作用。这只发生在Chrome。
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
maxlength属性对<input type="number">不起作用。这只发生在Chrome。
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
当前回答
许多人张贴的onKeyDown()事件根本不工作,即你不能删除一旦你达到限制。因此,使用onKeyPress()而不是onKeyDown(),它工作得很好。
下面是工作代码:
用户将不允许输入超过4位数字 < br > <input type="number" pattern="/^-?\d+\.? "\d*$/" onKeyPress="if(this.value.length==4) return false;"/>
其他回答
如果你想在React函数组件中实现它,或者不使用“this”,这里有一种方法。
<input onInput={handleOnInput}/>
const handleOnInput = (e) => {
let maxNum = 4;
if (e.target.value.length > maxNum) {
e.target.value = e.target.value.slice(0, maxNum);
}
};
<input type=“number” min=“1” onKeyPress=“if(this.value.length==5) 返回 false”/>
使用类型数字与min和处理max与onKeyPress
<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>
许多人张贴的onKeyDown()事件根本不工作,即你不能删除一旦你达到限制。因此,使用onKeyPress()而不是onKeyDown(),它工作得很好。
下面是工作代码:
用户将不允许输入超过4位数字 < br > <input type="number" pattern="/^-?\d+\.? "\d*$/" onKeyPress="if(this.value.length==4) return false;"/>
最大长度将不能与<input type="number"工作,我知道的最好的方法是使用oninput事件限制最大长度。请看下面的代码。
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
下面的代码将允许用户:
只能输入0-999范围内的数字。 这也限制了用户输入不超过3个字符。 当用户输入超过3个字符时,它将清除文本框。
<input type="number" name="test_name" min="0" max="999" oninput="validity.valid||(value='');">