6

I use the following to restricts user to enter only some characters. When I press tab, the cursor does not point to next control (in Mozilla). But it works fine in IE.

// Restricts user to enter characters other than a to z, A to Z and white space( )
// Rauf K. 06.11.2010
$("input:text.characters_only").keypress(function(e) {
if (!((e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) || e.which == 32 || e.which == 8 || e.which == 9)) {
        return false;
    }
});
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Rauf
  • 12,326
  • 20
  • 77
  • 126

2 Answers2

8

I would recommend trying e.keyCode instead of e.which. Here is a SO link that describes a good method of getting the key strike into a single variable regardless: jQuery Event Keypress: Which key was pressed?

Community
  • 1
  • 1
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
  • 3
    No, `keyCode` is the wrong property, because jQuery normalizes the `which` property. Most of the answers on the question you link to are hopelessly convoluted or misleading. – Tim Down Jan 25 '11 at 12:38
  • @Tim Down - I wasn't recommending all of the answers, just the accepted one. – Joel Etherton Jan 25 '11 at 12:39
  • 1
    @Tim: To repeat my comment from the other answer, as it really belongs here: I just tested this with Firefox using http://api.jquery.com/keypress : when I press , `e.which` isn't set (remains `0`), but `e.keyCode` is (`9`). – Marcel Korpel Jan 25 '11 at 12:43
  • 2
    @Marcel: Yes, fair point in this instance. In general, I would steer clear of using the `keyCode` property in a `keypress` handler: if you're interested in the physical key pressed use `keydown`, if you're interested in the character typed, use `keypress`. – Tim Down Jan 25 '11 at 12:49
  • @Tim: Indeed, but the OP wants to only allow certain key presses. If you want to catch that in a condition (and disallow everything else), you'll have to explicitly allow , too. I can't think of another solution in this case. – Marcel Korpel Jan 25 '11 at 12:57
  • which gives a 0 for escape also. Not sure why, maybe which is no good for non-characters? – studgeek Mar 04 '12 at 03:36
  • @TimDown, correct. Essentially `null !== event.which ? event.which : null !== event.charCode ? event.charCode : event.keyCode ....` (+ same for mouse events..button 1,2,...) –  Dec 09 '15 at 12:52
5

Perhaps if you start with something like:

if (e.keyCode === 9) { // TAB
    return true;
}
antonj
  • 21,236
  • 6
  • 30
  • 20