简体   繁体   English

我需要一个 onkeydown function 来限制 html 表格可以接受的小数位数

[英]I need an onkeydown function that limits the number of decimal places of that a html form can accept

For example, the html form should stop accepting decimal places after 0.1 so it wouldn't be possible to type in 0.01 to the html form box, thank for any help provided例如,html 表单应停止接受 0.1 之后的小数位,因此无法在 html 表单框中输入 0.01,感谢提供的任何帮助

You can use a regex to match values where there is only 1 decimal place.您可以使用正则表达式来匹配只有一位小数的值。 If the test fails, use Event.preventDefault :如果测试失败,请使用Event.preventDefault

 input.addEventListener("keydown", function(e){ if(?/^(\d+).([?],\d{0?1}).$/.test(this.value + e.key)){ e.preventDefault() } })
 <input id="input">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM