August 20, 2008 by Christoff Truter JavaScript
I've played around with JavaScript key press events quite a bit over the years.
The most comprehensive script I wrote around this subject, is a mask control which
we use on our intranet for all kinds of things (Code which I unfortunately can't
share with you, else I might get shot or something).
Just to get the ball on the roll (get the basics in place), lets imagine for a moment
that we want to hinder users to type anything but numeric values into a textbox
(obviously one would still need to have server side checks in place)
function numeric(e) { return ((e.keyCode == 8) || (e.keyCode > 47 && e.keyCode <58)); }
<input type="text" name="somename" onkeydown="return numeric(event)" />
function allowTab(sender, e) { if (e.keyCode == 9) { if (e.srcElement) { sender.selection = document.selection.createRange(); sender.selection.text = "\t"; } else if (e.target) { var start = sender.value.substring(0, sender.selectionStart); var end = sender.value.substring(sender.selectionEnd, sender.value.length); var newRange = sender.selectionEnd + 1; var scrollPos = sender.scrollTop; sender.value = String.concat(start, "\t", end); sender.setSelectionRange(newRange, newRange); sender.scrollTop = scrollPos; } return false; } else { return true; } }
<textarea name="somename" style="width:600px; height:600px" onkeydown="return allowTab(this, event)"> </textarea>
Thanks a lot... October 21, 2009 by Anonymous
Thank you very much for the tab key code. This is the only script that works for me until now. I've tried lots of stupid scripts but no success until this one.