js正则限制输入框只能输入实数
时间: 2023-08-21 20:01:43 浏览: 283
可以通过正则表达式限制输入框只能输入实数。以下是一个限制输入框只能输入实数的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>实数输入框</title>
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="realNumberInput" placeholder="只能输入实数">
<script>
var realNumberInput = document.getElementById("realNumberInput");
realNumberInput.oninput = function() {
this.value = this.value.replace(/[^\d\.\-]/g, ""); // 只保留数字、小数点和负号
this.value = this.value.replace(/^\./g, ""); // 第一个字符不能是小数点
this.value = this.value.replace(/\.{2,}/g, "."); // 不能同时输入多个小数点
this.value = this.value.replace(/\-\-/g, "-"); // 不能输入多个负号
this.value = this.value.replace(/\-$/g, ""); // 不能以负号结尾
this.value = this.value.replace(/^(\-?\d+)\.(\d\d).*$/, "$1.$2"); // 保留两位小数
}
</script>
</body>
</html>
```
这段代码中,我们首先获取了输入框元素,并为其绑定了`oninput`事件。在事件处理函数中,我们使用正则表达式限制了输入框只能输入数字、小数点和负号,并且对输入内容进行了一些限制,例如第一个字符不能是小数点,不能同时输入多个小数点等等。最后,我们使用正则表达式保留了两位小数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)