Keyboard restriction textbox with options and ñ





3.00/5 (7 votes)
Aug 30, 2005

53455

348
Javascript Keyboard Restrictions to apply in a textbox, n tilde ñ
Introduction
This is a single way to implement a character restriction in a page. Using this Javascript we can to restrict the input characters in a specific way for each control textbox.
Javascript Code
The code is simple, a getkeycode(event) returns the javascript keycode or event.which, depends on the browser.
function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
And a keyRestrict(event, validcharacters_string) returns a true or false if the key pressed is a valid character or not.
function keyRestrict(e, validchars) {
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}
Implementation
To use this is simple, just put a function call in the onkeypress event of the textbox
Numeric sample:
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'1234567890')">
Alfa (not alfanumeric just alfa in this case accepts a SPACE)
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'abcdefghijklmnopqrstuvwxyz ')">
Ñ support (spanish keyboards for example).
Here a sample with the Ñ support. because if you type the 'ñ' in the string the script fail in the moment you press the ñ char.
to have Ñ suport we need to put the next code:
<input type="text" name="textfield" onKeyPress="return keyRestrict(event,'abcdefghijklmnopqrstuvwxyz '+String.fromCharCode(241))">
this is a simple script, but the Ñ support is usefull to me, and i wabt to share the solution