JavaScript Events: OnError, OnFocus and More - OnKeyDown
(Page 4 of 6 )
You can trigger an event to occur when a user presses a key on his keyboard by using the OnKeyDown event. In the sample below we are going to use an OnKeyDown event to ensure that the user enters only text (and no numbers or special characters) into the text box.
<html>
<body>
<script type="text/javascript">
function textonly(e)
{
var keys
var letter
var numberchecker
if(window.event) // Internet Explorer
{
keys = e.keyCode
}
else if(e.which) // Netscape/Opera/FireFox
{
keys = e.which
}
letter = String.fromCharCode(keys)
numberchecker = /d/
return !numberchecker.test(letter)
}
</script>
<form>
Name (no numbers please):
<input type="text" onkeydown="return textonly(event)" />
</form>
</html>
As you can see, if the user tries to enter numbers into the text field, nothing happens. You will also note that Internet Explorer and Netscape, Firefox, and Opera use different coding (window.event, e.which) for the OnKeyDown event.
Supporting HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <del>, <dfn>, <div>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var>
Supporting Javascript Objects: document, image, link, textarea
Next: OnKeyPress >>
More JavaScript Articles
More By James Payne