Capture *all* display-characters in JavaScript?

Posted by Jean-Charles on Stack Overflow See other posts from Stack Overflow or by Jean-Charles
Published on 2010-04-21T16:19:36Z Indexed on 2010/04/21 16:23 UTC
Read the original article Hit count: 400

I was given an unusual request recently that I'm having the most difficult time addressing that involves capturing all display-characters when typed into a text box. The set up is as follows:

I have a text box that has a maxlength of 10 characters. When the user attempts to type more than 10 characters, I need to notify the user that they're typing beyond the character count limit.

The simplest solution would be to specify a maxlength of 11, test the length on every keyup, and truncate back down to 10 characters but this solution seems a bit kludgy. What I'd prefer to do is capture the character before keyup and, depending on whether or not it is a display-character, present the notification to the user and prevent the default action.

A white-list would be challenging since we handle a lot of international data.

I've played around with every combination of keydown, keypress, and keyup, reading event.keyCode, event.charCode, and event.which, but I can't find a single combination that works across all browsers. The best I could manage is the following that works properly in >=IE6, Chrome5, FF3.6, but fails in Opera:

NOTE: The following code utilizes jQuery.

$(function(){
  $('#textbox').keypress(function(e){
    var $this = $(this);
    var key = ('undefined'==typeof e.which?e.keyCode:e.which);
    if ($this.val().length==($this.attr('maxlength')||10)) {
      switch(key){
        case 13: //return
        case 9:  //tab
        case 27: //escape
        case 8:  //backspace
        case 0:  //other non-alphanumeric
          break;
        default:
          alert('no - '+e.charCode+' - '+e.which+' - '+e.keyCode);
          return false;
      };
    }
  });
});

I'll grant that what I'm doing is likely over-engineering the solution but now that I'm invested in it, I'd like to know of a solution. Thanks for your help!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events