[英]keydown event - key pressed on different systems
I have a number input, which I want user to by unable to insert any non-digit characters. 我有一个数字输入,我希望用户无法插入任何非数字字符。 We have attempted this in a number of ways:
我们以多种方式尝试了此操作:
We started with removing all non-numeric characters on blur: 我们首先删除模糊时的所有非数字字符:
$(my_input).blur(function() {
$(this).val($(this).val().replace(/[^\d]/, '')
}
The problem with the code above is that number field's val
function returns empty string if the input is invalid. 上面的代码的问题是,如果输入无效,那么number字段的
val
函数将返回空字符串。 We definitively want a number field as our website is to be used on mobiles. 我们绝对希望有一个数字字段,因为我们的网站将在手机上使用。
The option which I would prefer is to use keydown
event: 我更喜欢的选项是使用
keydown
事件:
$(my_input).keydown(function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
});
The above works almost as a charm. 以上几乎是一种魅力。 The problems are:
问题是:
numeric keyboard not included in a range - this can be however easily fixed and is not a subject of this question. 数字键盘不包含在范围内-但是可以轻松解决,而不是此问题的主题。
For unknown to me reasons js on iOS is using different key codes, hence this is not working on huge part of mobile phones, iPads etc.. This is a deal breaker. 出于我未知的原因,iOS上的js使用不同的键代码,因此在手机,iPad等的很大一部分上均无法使用。这是一个大问题。
So the question - is there any way to determine which key was actually pressed with an keydown
event. 因此,问题-是否有任何方法可以确定在按下
keydown
事件时实际按下了哪个键。 I have seen number of similar questions, none of them however covered those iOS differences. 我见过许多类似的问题,但是没有一个涵盖了iOS的差异。 I've noticed that event has a 'key' property, however I am not sure how reliable this property is.
我注意到该事件具有“键”属性,但是我不确定该属性的可靠性。
EDIT: I fell on this post which might be a neat way to solve your problem: JavaScript: Avoiding hardcoded keycodes 编辑:我掉在这篇文章上,这可能是解决您的问题的一种好方法: JavaScript:避免使用硬编码的键码
It would boil down to 它会归结为
var digitCodes = "0123456789".split('').map(function (x) { return x.charCodeAt(0); });
There might be a better way to do this but you could detect if the device is running iOS (cf Detect if device is iOS ) and use the appropriate keycodes (cf http://notes.ericjiang.com/posts/333 ). 也许有更好的方法来执行此操作,但是您可以检测设备是否正在运行iOS(请参阅检测设备是否为iOS )并使用适当的键码(请参阅http://notes.ericjiang.com/posts/333 )。
var digitCodes;
if (isiOS()) {
digitCodes = keycodes.ios;
}
else {
digitCodes = keycodes.default;
}
if (digitCodes.indexof(e.which) != -1) {
...
}
Something like that... 像那样
You can try it this way 你可以这样尝试
sample text box 示例文本框
<input type="text" name="sample" id="sample" onkeyup="positiveNumericOnly(this);" />
JS Code JS代码
function positiveNumericOnly(ele)
{
tempVal = ele.value.replace(/[^\d]/g, "");
if(tempVal != ele.value)
ele.value = tempVal;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.