using jQuery here, however unable to prevent numbers from being typed into the input field
http://codepen.io/leongaban/pen/owbjg
Input
<input type="text" name="field" maxlength="8" title="Only Letters" value="Type Letters Only" onkeydown="return alphaOnly(event);" onblur="if (this.value == '') {this.value = 'Type Letters Only';}" onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>
jQuery
function alphaOnly(event) { alert(event); var key; if (window.event) { key = window.event.key; } else if (e) { key = e.which; } //var key = window.event.key || event.key; alert(key.value); return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122)); }
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?
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.
To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
Short ONELINER:
<input onkeydown="return /[a-z]/i.test(event.key)" >
For all unicode letters try this regexp: /\p{L}/u
(but ... this) - and here is working example :)
The property event.key
gave me an undefined value. Instead, I used event.keyCode
:
function alphaOnly(event) { var key = event.keyCode; return ((key >= 65 && key <= 90) || key == 8); };
Note that the value of 8 is for the backspace key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With