Use the keypress
event instead. It's the only key event which will give you information about the character that was typed, via the which
property in most browsers and (confusingly) the keyCode
property in IE. Using that, you can conditionally suppress the keypress
event based on the character typed. However, this will not help you prevent the user from pasting or dragging in text containing numeric characters, so you will still need some kind of extra validation.
My favourite reference for JavaScript key events: http://unixpapa.com/js/key.html
textBox.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
var charStr = String.fromCharCode(charCode);
if (/d/.test(charStr)) {
return false;
}
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…