• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Managing Events > 9.8. Reading Which Character Key Was Typed

Reading Which Character Key Was Typed

NN 4, IE 4

Problem

You want to inspect each alphanumeric key typed by the user before the character reaches a form field.

Solution

The following function should be invoked by an onkeypress event handler bound to a text input field in which you want to limit characters to the digits 0 through 9, a minus sign, and a decimal:

function numberOnly(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
       var elem = (evt.target) ? evt.target : 
          ((evt.srcElement) ? evt.srcElement : null);
       if (elem) {
           var charCode = (evt.charCode) ? evt.charCode : 
               ((evt.which) ? evt.which : evt.keyCode);
           if ((charCode < 32 ) || 
               (charCode > 44 && charCode < 47) || 
               (charCode > 47 && charCode < 58)) {
               return true;
           } else {
               return false;
           }
       }
    }
}

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint