[英]form input restrict number only
I have a script to set the form input as number only... but it is working only in desktop.我有一个脚本可以将表单输入设置为仅数字......但它只在桌面上工作。 While trying in mobile the same is not working.
在移动设备中尝试时,同样不起作用。 What is the problem?
问题是什么?
<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>
This is the form input and below is the javascript used for the form这是表单输入,下面是用于表单的 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>
You can restrict form input to allow number only.您可以将表单输入限制为仅允许数字。
$(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" />
Change the input field to type="number" instead of type="text".将输入字段更改为 type="number" 而不是 type="text"。
You can simply use isNaN() function.您可以简单地使用 isNaN() function。 It will return if the value is "Not a Number".
如果值为“非数字”,它将返回。 You can then write your code like this:
然后,您可以像这样编写代码:
if(!isNaN(e)){
//Your code here
}
You can use input type="number" and some CSS to show and hide the message.您可以使用 input type="number" 和一些 CSS 来显示和隐藏消息。
To keep the error from appearing before, you can add a class.为了避免之前出现错误,您可以添加一个 class。 This will not prevent the user from typing invalid characters.
这不会阻止用户输入无效字符。
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.