JS function to allow enter only letters and white spaces

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 :

<input id="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


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

HTML

<input id="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();
        return false;
    }
});

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();
        return false;
    }
}