JQuery验证代码不允许删除输入的文本 [英] JQuery validation code will not allow deletion of entered text
问题描述
我从这个问题中借了一些代码(见回复4):
I borrowed a bit of code from this question (see reply 4):
然而,在使用代码时,看来虽然它在您输入的时候进行了验证,但它不允许您编辑您输入的任何内容。
However, upon using the code, it appears, that although it does the validation as you type neatly, it does not allow you to edit anything you have entered.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}});
我有点困惑,我试图通过将按键更改为keyup来调整它,但这只是停止验证工作。任何指针都会被慷慨地接受。
I am a bit confused, I have tried to adjust it by changing the keypress to keyup but this just stops the validation from working. Any pointers would be graciously accepted.
推荐答案
这似乎是一个特定于浏览器的问题。在Firefox中,keypress包括退格键和箭头键等元键,而Chrome则不包括。如果你稍微调整你的逻辑以更喜欢哪个超过charCode(我认为最好支持它)你最终得到这个
This seems to be a browser specific issue. In Firefox keypress includes meta keys like backspace and the arrow keys while Chrome does not. If you adjust your logic a bit to prefer which over charCode (which I think is better supported anyways) you end up with this
$('input').bind('keypress', function(event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var code = event.charCode === 0 ? event.which : event.charCode;
var key = String.fromCharCode(code);
if (!regex.test(key) && code !== 8) {
// 8 is ascii code for backspace
event.preventDefault();
return false;
}
});
这个小提琴还会向控制台写入键入时输入的键和代码。
http://jsfiddle.net/Q2MWS/5/
This fiddle also writes to console the keys and codes being passed in the event when typing. http://jsfiddle.net/Q2MWS/5/
这篇关于JQuery验证代码不允许删除输入的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!