Skip to content Skip to sidebar Skip to footer

Js Function To Allow Enter Only Letters And White Spaces

I need a jquery or js function to only allow enter letters and white spaces. Thanks in advance. page: function: function onlyLett

Solution 1:

The following code allows only a-z, A-Z, and white space.

HTML

<inputid="inputTextBox"type="text" />

jQuery

$(document).on('keypress', '#inputTextBox', function (event) {
    var regex = new RegExp("^[a-zA-Z ]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        returnfalse;
    }
});

Solution 2:

Note: KeyboardEvent.which is deprecated as of Jan. 1, 2020

Just use ascii codes (decimal values) of keys/digits that you want to disable or prevent from being work. ASCII Table .

HTML :

<inputid="inputTextBox"type="text" />

jQuery :

$(document).ready(function(){
    $("#inputTextBox").keydown(function(event){
        var inputValue = event.which;
        // allow letters and whitespaces only.if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { 
            event.preventDefault(); 
        }
    });
});

jsFiddle Demo

Solution 3:

First off, I have little experience in jQuery and will provide a vanilla javascript example. Here it is:

document.getElementById('inputid').onkeypress=function(e){
    if(!(/[a-z ]/i.test(String.fromCharCode(e.keyCode))) {
        e.preventDefault();
        returnfalse;
    }
}

Solution 4:

Tweaking Ashad Shanto answer a bit. Notice you cant type in y and z if you use the script. You have to change the inputValue from 120 to 123. Here is the ASCII table reference: http://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html Use the script below to type in all the letters, space and backspace.

<script>
    $(document).ready(function(){
        $("#inputTextBox").keypress(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
    });

</script>

Solution 5:

you could use this simple method, that I took from this post

<input type="text" name="fullName" onkeypress="return (event.charCode > 64 && 
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" 
placeholder="Full Name">

Post a Comment for "Js Function To Allow Enter Only Letters And White Spaces"