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
});
}
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;
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With