[英]form input restrict number only
我有一个脚本可以将表单输入设置为仅数字......但它只在桌面上工作。 在移动设备中尝试时,同样不起作用。 问题是什么?
<input class="input--style-4" type="text" name="field6" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"required>
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
这是表单输入,下面是用于表单的 javascript
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
您可以将表单输入限制为仅允许数字。
$(document).ready(function () { // Allow number only for html input text $(document).on('keypress', ':input[name="qty"]', function (e) { if (isNaN(e.key)) { return false; } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="qty" type="text" name="qty" />
将输入字段更改为 type="number" 而不是 type="text"。
您可以简单地使用 isNaN() function。 如果值为“非数字”,它将返回。 然后,您可以像这样编写代码:
if(!isNaN(e)){
//Your code here
}
您可以使用 input type="number" 和一些 CSS 来显示和隐藏消息。
为了避免之前出现错误,您可以添加一个 class。 这不会阻止用户输入无效字符。
span.error { color: red; display: none; } input.hadInput:invalid + span.error { display: block; }
<input class="input--style-4" type="number" name="field6" oninput="this.classList.add('hadInput')" required> <span class="error">* Input digits (0 - 9)</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.