Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<p:inputText onkeypress="onlyLetter(this)">

function:

function onlyLetter(input){
    $(input).keypress(function(ev) {
   var keyCode = window.event ? ev.keyCode : ev.which;
  //  code

    });
}
like image 834
user2683519 Avatar asked Nov 07 '13 23:11

user2683519


2 Answers

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;
    }
});
like image 195
VIJAY P Avatar answered Nov 10 '22 14:11

VIJAY P


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

like image 45
Md Ashaduzzaman Avatar answered Nov 10 '22 13:11

Md Ashaduzzaman