我需要避免在文本类型输入字段中输入数字。我的应用程序仅在 iPhone 和 Android 等设备中使用。
为此我尝试使用以下代码:
$("#custName-info").keypress(function (event) {
alert(event.charCode);
var inputValue = event.charCode;
if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
这里,代码在 iPhone 上运行得很好,但在 Android 设备上却不起作用。经过调查,我发现了以下信息:
- keypress 已被弃用,因此应避免使用。但如果这就是原因,为什么它可以在我的 iPhone 或 Chrome 设备模拟器上运行?
- 人们建议使用以下三个替代事件之一:
keyup、keydown、input、change
- 我进一步发现这 3 个事件中的任何一个在设备中都不适用于我,因为它们没有给我
charCode
来识别数字输入。 keyCode
上有一些内容,但我无法理解charCode
和keyCode
之间有什么区别
所以我对这个问题的最后一句话是,“如何阻止用户在文本字段中输入数字?iPhone 和 Android 设备中使用的 Web 应用程序”。
最佳答案
这对你有用吗?
$("#custName-info").on("input",function(event) {
var inputValue = this.value;
console.log(inputValue);
this.value = this.value.replace(/[0-9]/g,"")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="custName-info" />
请访问https://bugs.chromium.org/p/chromium/issues/detail?id=118639#c283
原始答案无效:
按照
中的建议,我将keypress
替换为 keydown
,将 charCode
替换为 which
JavaScript KeyCode vs CharCode
FIDDLE - 在 iOS 中仍然有效
$("#custName-info").on("keydown",function(event) {
var inputValue = event.which;
console.log(inputValue);
if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="custName-info" />
关于javascript - 使用 Javascript 或 jQuery 防止在文本字段中输入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50945186/