2

How can I ensure that user press "printable" character in jquery?

I try this but it doesn't work

$("#foo").keyup(function (e) {
    if (e.charCode) {
        console.debug('this is printable char');
    }
});

I would want only numbers, A-Z a-z character, and also "è,$,%" etc, but not arrow, enter,f5 etc

paganotti
  • 5,591
  • 8
  • 37
  • 49

2 Answers2

1

Try:

$("#foo").keyup(function (e) {
    if (e.which < 0x20) {
        console.debug('this is not printable char');
        return;
    }
    else {
        console.debug('this is printable char');
    }
});
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0
<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

Courtesy

Community
  • 1
  • 1
Ankur Verma
  • 5,793
  • 12
  • 57
  • 93