views:

791

answers:

3

I tried searching but unsure of what terms to look for.

I'm using jQuery and would like to use the keypress event in a textbox, but prevent all non-printable characters (ie. Enter, ESC, arrow keys, backspace, tab, ctrl, insert, F1-F12, etc) from triggering the event.

Is there an easy way to determine if it is printable?

A: 

You can use regular expressions like this

$('something').keypress(function(e) {
    if(e.match(YourRegularExpressionHere)) {
        //do something
    } 
});

This will only do something if it matches the regular expression.

Have a look at regular expressions. http://www.regular-expressions.info/javascript.html

Catfish
+3  A: 
<script type="text/javascript">
    $("input").keypress(function (e) {
        if (e.which !== 0 && e.charCode !== 0) {
            alert(String.fromCharCode(e.keyCode|e.charCode));
        }
    });
</script>

Seems tow work just fine with jQuery 1.4.2, FF, IE, Chrome.

To delve into the mess that is JS keyboard event handling, see: JavaScript Madness: Keyboard Events

andras
Thanks, thats similar to the solution I ended up implementing!
twig
A: 
/* handle special key press */
function checkCptKey(e)
{
    var shouldBubble = true;
    switch (e.keyCode)
    {
        // user pressed the Tab                                                                                                                                                                      
        case 9:
            {
                $(".cptIcdProcedureSelect").toggleClass("cptIcdProcedureSelectVisible");
                 shouldBubble = false;
                break;
            };
            // user pressed the Enter    
        case 13:
            {
                $(".cptIcdProcedureSelect").toggleClass("cptIcdProcedureSelectVisible");
                break;
            };
            // user pressed the ESC
        case 27:
            {
                $(".cptIcdProcedureSelect").toggleClass("cptIcdProcedureSelectVisible");
                 break;
            };
    };
    /* this propogates the jQuery event if true */
    return shouldBubble;
};
   /* user pressed special keys while in Selector */
   $(".cptCode").keydown(function(e)
   {
       return checkCptKey(e, $(this));
   });
Mark Schultheiss