JavaScript Text Only Input

10 12 2007

This function can be used on the onkeypress event of a HTML input box to only allow entry of text charactes: A-Z, a-z, dash, space, and backspace.

Usage:

<input type="text" id="name" onkeypress="return textonly(event);" /> 

Javascript:

function textonly(e){
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
//alert('Character was ' + character);
    //alert(code);
    //if (code == 8) return true;
    var AllowRegex  = /^[\ba-zA-Z\s-]$/;
    if (AllowRegex.test(character)) return true;    
    return false;
}


Actions

Information

Leave a comment