1

I have to disable some symbols from html input. e.which is not working properly on Firefox. Firefox disables backspace and ect. Here is JS Fiddle:

var code = window.event ? event.keyCode : e.which;

event.keyCode works on firefox, but does not work with String.fromCharCode(code).

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
Srw
  • 69
  • 10

2 Answers2

2

jQuery normalizes e.which, so you don't have to worry about this at all.
Also, it's a lot easier to just listen for the correct keycodes, there's no reason to convert the keycode to a character just to filter it out with indexOf ?

$('#foo').keydown(function(e) {
    var code = e.which;
    if (code == 8 || code == 13) return true; // backspace and enter
    if (code < 48 || code > 57 || code == 188 || code == 190) return false;
});

FIDDLE

To keep most keys active, and just mainly disable characters, you could filter like this

$('#foo').keydown(function(e) {
    var key = e.which;
    if (!e.shiftKey && !e.altKey && !e.ctrlKey && 
        key >= 48 && key <= 57 ||  // numbers   
        key >= 96 && key <= 105 || // Numeric keypad
        key == 190 || key == 188 || key == 109 || key == 110 || // comma, period and minus, . on keypad
        key == 8 || key == 9 || key == 13 ||  // Backspace and Tab and EnterEnd
        key == 35 || key == 36 || // Home and 
        key == 37 || key == 39 || // left and right arrows
        key == 46 || key == 45) // Del and Ins
        return true;

    return false;
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Backspace STILL NOT WORKING on firefox - that is main problem – Srw Jan 11 '14 at 12:06
  • 1
    @Srw - You're blocking everything **BUT** numbers, comma and period, of course backspace doesn't work, if you'd like to allow that character you have to add it to a whitelist, I'll update the answer. – adeneo Jan 11 '14 at 12:07
  • now i need arrow, del and ect. )) what is general solution to affect only symbols? – Srw Jan 11 '14 at 12:11
  • What you gonna do with russian keyboard layout, shift+? puts a dot on it. Shall i look after Shift key? – Srw Jan 13 '14 at 09:50
0

You've got two errors in your script:

  1. you called the event parameter event but referred to e.which.

2. you have to call evt.preventDefault() for preventing the typed character to appear.
The latter point is wrong when adding jQuery event handlers. 'Normal' DOM handlers require preventDefault(), see also this comment.


→ jsFiddle

$('#foo').keypress(function(evt) {
    var code = window.event ? event.keyCode : evt.which;
    var chr = String.fromCharCode(code);
    if ("0123456789.,".indexOf(chr) < 0) {
        return false;
    }
});
Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156