应该只接受正整数,javascript,html"/>

首页 > 解决方案 > 应该只接受正整数

问题描述

这个 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 之间

标签: javascripthtml

解决方案


您可以为元素设置一个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>


推荐阅读