Javascript Function to enter only alphabets on keypress

Lucy picture Lucy · May 20, 2013 · Viewed 84.7k times · Source

I want to enter only character values inside a <textarea> and numeric values in another. I have been able to make a JavaScript function which only allows numeric values to be entered in the <textarea> using onkeypress. This works in Firefox and Chrome.

For alphabets I am creating another JavaScript function using windows.event property. Only problem is this works only in Chrome and not in Firefox.

I want to know how to allow only alphabets to be entered using onkeypress event as used for entering only numeric values?

Answer

Hrushi picture Hrushi · Jun 15, 2016
function lettersOnly() 
{
            var charCode = event.keyCode;

            if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)

                return true;
            else
                return false;
}

<input type="text" name="fname" value="" onkeypress="return lettersOnly(event)"/>