Javascript Function to enter only alphabets on keypress
Asked Answered
P

7

11

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>
Pyrotechnics answered 20/5, 2013 at 10:21 Comment(6)
"only character values" - Do you mean only letters? Remember that validating on keypress is not sufficient, because the user may copy/paste or drag'n'drop without causing a keypress event.Ethiopian
use regular expressions instead?Tornado
Here are some examples of characters: "1", "&", "a", ")", "W". You mean letters.Ethiopian
yes i want to use letters like A,a,b,BPyrotechnics
Refer chandanprogramming.blogspot.in/2013/05/…Surfeit
Did you check it on latest firefox 45.0 ? it is not workingGramophone
B
10
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)"/>
Bourque answered 15/6, 2016 at 12:44 Comment(0)
L
6

If you don't need to support older browsers I would use the input event. This way you can also catch non-alpha characters if the user pastes text into the textarea.

I cleaned up your HTML a little bit. The most important changes are to the events on cname and cnum. Note that the event in both cases has been changed to oninput.

<label for="cname" class="label"> The Risk Cluster Name</label>
<textarea id="cname" rows="1" cols="20" style="resize:none" placeholder="Cluster Name" oninput="validateAlpha();"></textarea>
<label for="cnum">Risk Cluster Number:</label>
<textarea id="cmun" rows="1" cols="12" style="resize:none" placeholder="Cluster Number" oninput="isNumberKey();"></textarea><br /><br /><br />

Assuming you want cname to only accept characters in the alphabet and cnum to only accept numbers, your JavaScript should be:

function validateAlpha(){
    var textInput = document.getElementById("cname").value;
    textInput = textInput.replace(/[^A-Za-z]/g, "");
    document.getElementById("cname").value = textInput;
}
function isNumberKey(){
    var textInput = document.getElementById("cmun").value;
    textInput = textInput.replace(/[^0-9]/g, "");
    document.getElementById("cmun").value = textInput;
}

This code uses regular expressions, a way to match patterns in strings.

Leatriceleave answered 25/12, 2013 at 8:55 Comment(0)
S
2

Best Uses

<input type="text" name="checkno" id="checkno" class="form-control"  value="" onkeypress="return isNumber(event)"/>

<input type="text" name="checkname" id="checkname" class="form-control" value="" onkeypress="return isAlfa(event)"/>


function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function isAlfa(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
        return false;
    }
    return true;
}
Suppressive answered 22/1, 2016 at 11:59 Comment(0)
G
1
function digitonly(input,event){    

        var keyCode = event.which ? event.which : event.keyCode;
        var lisShiftkeypressed = event.shiftKey;
        if(lisShiftkeypressed && parseInt(keyCode) != 9){return false;}
        if((parseInt(keyCode)>=48 && parseInt(keyCode)<=57) || keyCode==37/*LFT ARROW*/ || keyCode==39/*RGT ARROW*/ || keyCode==8/*BCKSPC*/ || keyCode==46/*DEL*/ || keyCode==9/*TAB*/  || keyCode==45/*minus sign*/ || keyCode==43/*plus sign*/){return true;}     
        BootstrapDialog.alert("Enter Digits Only"); 
        input.focus();
        return false;           
}

function alphaonly(input,event){

        var keyCode = event.which ? event.which : event.keyCode;
        //Small Alphabets
        if(parseInt(keyCode)>=97 && parseInt(keyCode)<=122){return true;}
        //Caps Alphabets
        if(parseInt(keyCode)>=65 && parseInt(keyCode)<=90){return true;}
        if(parseInt(keyCode)==32 || parseInt(keyCode)==13 || parseInt(keyCode)==46 || keyCode==9/*TAB*/ || keyCode==8/*BCKSPC*/ || keyCode==37/*LFT ARROW*/ || keyCode==39/*RGT ARROW*/ ){return true;}
        BootstrapDialog.alert("Only Alphabets are allowed") 
        input.focus();
        return false; 
}

Graeae answered 22/3, 2018 at 11:43 Comment(0)
C
0

hi try below code it worked for me in all browsers, it allows numbers and few special characters like,.+-() : in the textbox use as follows

<asp:Textbox Id="txtPhone" runat="server" onKeyPress="return onlyNumbersandSpecialChar()">     </asp:Textbox>

function onlyNumbersandSpecialChar(evt) {
    var e = window.event || evt;
    var charCode = e.which || e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 ||          charCode > 221) && charCode != 40 && charCode != 32 && charCode != 41 && (charCode < 43 || charCode > 46)) {
        if (window.event) //IE
            window.event.returnValue = false;
        else //Firefox
            e.preventDefault();
    }
    return true;

   }

 </script>
Cautious answered 30/5, 2013 at 10:22 Comment(1)
thanks for the code but i wanted to input only alphabets(lower&upper case) and some special characters like ",.+-:" and space between alphabets as well....so can you please edit your answer accordingly...Pyrotechnics
C
0

as charCode and keyCode are now deprecated it is recommended to use the key property. Also, The onkeypress event is deprecated, it is better to use onkeydown . Hence I would do something like this

var keydowns = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", 
                "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Meta", 
                "Alt", "Control", "Shift", "CapsLock", "Tab", "Escape"];

function lettersOnly(event) {
     const key = event.key;
     if ( keydowns.includes(key) ) {
        return true;
     };
     else {
        return false;
     };

<input type="text" name="fname" value="" onkeydown="return lettersOnly(event)"/>
Chabot answered 6/6, 2023 at 22:57 Comment(0)
J
0

function alphaOnly(event) {
        var key = event.keyCode;
        var inputValue = event.target.value;
        
        if (key === 190 && event.key === '>') {
            return false;
        }

        if ((key >= 65 && key <= 90) || key == 8 || (key == 190 && inputValue.lastIndexOf(".") < inputValue.length - 1) ||
            (key == 32 && inputValue.lastIndexOf(" ") < inputValue.length - 1)) {
            return true;
        } else {
            return false;
        }
    };
<div id="nameDiv">
                <label for="nameId">Name<b id="starText">*</b></label> <input
                    id="nameId" type="text" name="name" placeholder="Enter name here"
                    maxlength="60" 
                    minlength="3"
                    onkeydown="return alphaOnly(event)" required>
            </div>

function alphaOnly(event) {

    var key = event.keyCode;
    var inputValue = event.target.value;
    
    if (key === 190 && event.key === '>') {
        return false;
    }

    if ((key >= 65 && key <= 90) || key == 8 || (key == 190 && inputValue.lastIndexOf(".") < inputValue.length - 1) ||
        (key == 32 && inputValue.lastIndexOf(" ") < inputValue.length - 1)) {
        return true;
    } else {
        return false;
    }
};
Jibber answered 15/2 at 4:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.