using jQuery here, however unable to prevent numbers from being typed into the input field
http://codepen.io/leongaban/pen/owbjg
Input
JavaScript
x
7
1
<input type="text" name="field" maxlength="8"
2
title="Only Letters"
3
value="Type Letters Only"
4
onkeydown="return alphaOnly(event);"
5
onblur="if (this.value == '') {this.value = 'Type Letters Only';}"
6
onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>
7
jQuery
JavaScript
1
17
17
1
function alphaOnly(event) {
2
3
alert(event);
4
5
var key;
6
7
if (window.event) {
8
key = window.event.key;
9
} else if (e) {
10
key = e.which;
11
}
12
//var key = window.event.key || event.key;
13
alert(key.value);
14
return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122));
15
16
}
17
I’ve seen plenty of examples here on how to restrict to only Numbers, and I’m using the correct key codes for a-z and A-Z. Do you see what I’m doing wrong?
Advertisement
Answer
The property event.key
gave me an undefined value. Instead, I used event.keyCode
:
JavaScript
1
5
1
function alphaOnly(event) {
2
var key = event.keyCode;
3
return ((key >= 65 && key <= 90) || key == 8);
4
};
5
Note that the value of 8 is for the backspace key.