[英]How to accept only number in the input field using js
如何使用js事件监听器使输入框只接受输入字段中的数字。
<form action="#">
<label for="value">Value:</label>
<input type="text" name="value" id="value" />
<button type="submit">Convert</button>
<button type="reset">Clear</button>
</form>
<script>
form.addEventListener(`submit`, function(event){
event.preventDefault();
});
</script>
您可以将输入解析为数字,然后检查它是数字还是其他类似 NaN 的东西。
if(typeof parseInt(input) ==="number"){
console.log("number!");
}
请注意,任何人都可以使用开发工具绕过此问题,因此不要忘记实施服务器端验证。(提示@samathingamajig)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.