javascript - 应该只接受正整数
问题描述
这个 HTML 代码仍然允许我编写.
因此,如果用户写入1.2
将自动转换为12
.
我不想让用户自己写.
。
此外,虽然它不允许用户从-
标志开始,但它允许用户在中间输入它,21-
但它会立即将整个字段重置为空白。
我该如何解决这个问题,使它只接受正整数?
<input type="number" min="30" max="300" step="1" oninput="validity.valid||(value=value.replace(/\D+/g, ''))" style="width:4em" id="seconds" name="seconds" value="30" onmouseout="setBounds()" />
setBounds() 具有功能,因此用户只能输入 30 到 300 之间
解决方案
您可以为元素设置一个keypress
事件处理程序,该处理程序检查正在按下的键并在.
或-
条目上取消事件event.preventDefault()
,如下所示:
const input = document.getElementById("seconds");
// Set your event handlers up in JavaScript, not with
// inline HTML event attributes
input.addEventListener("keypress", function(event){
if(event.key === "." || event.key === "-"){
event.preventDefault(); // Cancel the native operation
}
});
<input type= "number" min="30" max="300" step="1" id="seconds" name="seconds" value="30">
但是,因为您有一个特定的范围,您可能需要考虑使用一个input type="range"
首先消除问题可能性的方法:
// Get reference to the input and the output elements
const input = document.getElementById("seconds");
const output = document.getElementById("output");
output.textContent = input.value; // Initialize the output
// Set your event handlers up in JavaScript, not with
// inline HTML event attributes
input.addEventListener("input", function(event){
output.textContent = this.value; // Update the output
});
<input type= "range" min="30" max="300" step="1" id="seconds" name="seconds" value="30">
<span id="output"></span>
推荐阅读
- sql - Postgresql:是否可以判断在哪一列中找到了搜索字符串?
- wordpress - Wordpress/htaccess - 允许访问子目录
- sql - 如果表的视图仍在使用中,如何限制表被删除
- c# - 在 C# 中查找和获取具有特定属性的 XML 行
- activeweb - ActiveWeb:模拟注入服务
- keras - Keras-VGG16-places365 低准确率问题
- c# - 通过 HttpWebRequest 从页面转发隐藏字段
- html - 在 Opera/Chrome 浏览器中滚动时,粘性导航栏在某一点闪烁(渲染错误?)
- google-apps-script - 您可以将所有文本“存储”在谷歌文档中并在某人的编辑上重新写回吗?
- reactjs - React 组件道具样式