Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

html - Javascript Function to enter only alphabets on keypress

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?

function isNumberKey(evt){  <!--Function to accept only numeric values-->
    //var e = evt || window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode != 46 && charCode > 31 
&& (charCode < 48 || charCode > 57))
        return false;
        return true;
}
   
    function ValidateAlpha(evt)
    {
        var keyCode = (evt.which) ? evt.which : evt.keyCode
        if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)
         
        return false;
            return true;
    }
<label for="cname" class="label">The Risk Cluster Name</label>
<textarea id="cname" rows="1px" cols="20px" style="resize:none" placeholder="Cluster Name" onKeyPress="return ValidateAlpha(event);"></textarea>
<br>
<label for="cnum">Risk Cluster Number:</label>
<textarea id="cmun" rows="1px" cols="12px" style="resize:none" placeholder="Cluster Number" onkeypress="return isNumberKey(event)"></textarea>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...