title: JavaScript Key Codes
body: <p>I'm working with a JavaScript routine I didn't write. It is called from a text box's <code>onkeydown</code> attribute to prevent unwanted keystrokes.</p>
  
  <p>The first argument is apparently not used. The second argument is a list of characters that should be allowed.</p>
  
  <pre><code>function RestrictChars(evt, chars) {
      var key;
      var keychar;
  
      if (window.event)
          key = window.event.keyCode;
      else if (e)
          key = e.which;
      else
          return true;
  
      keychar = String.fromCharCode(key);
  
      if ((key == null) || (key == 0) || (key == 8) ||
          (key == 9) || (key == 13) || (key == 27))
          // Control key
          return true;
      else if (((chars).indexOf(keychar) &gt; -1))
          return true;
      else
          return false;
  }
  </code></pre>
  
  <p>This seems to work for alpha-numeric characters. However, characters such as <code>.</code> and <code>/</code> cause this function to return <code>false</code>, even when these characters are included in the <code>chars</code> parameter. For example, if the <code>.</code> key is pressed, <code>key</code> is set to 190, and <code>keychar</code> gets set to the "3/4" character.</p>
  
  <p>Can anyone see how this was meant to work and/or why it doesn't? I don't know enough about JavaScript to see what it's trying to do.</p>