tags:

views:

280

answers:

2

I want to make the text box allow only alphabets (a-z) using Jquery? Any examples.

Thanks in advance.

+1  A: 
<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">

And can be the same to onblur for evil user who like to paste instead of typing ;)

[+] Pretty jQuery code:

<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    $(this).val( $(this).val().replace(/[^a-z]/g,'') ); }
);
</script>
dev-null-dweller
You shouldn't use HTML attributes to attach events, especially when something as easy as jQuery is available to properly attach the event handler.
Justin Johnson
Now I used yours.On that day I did one mistake.But now I solved that.It works fine for me.
vinothkumar
+2  A: 

To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.

Or, alternatively use one of the many input mask plugins out there.

See example.

​$(<selector>).keypress(function(e) {
    if(e.which < 97 /* a */ || e.which > 122 /* z */) {
        e.preventDefault();
    }
});​​​​​
Anurag
But I cant delete it?Is it possible to delete?
vinothkumar
Nice, but still needs some tweaks to prevent from pasting after right click
dev-null-dweller