2

I have created a function for input mask with jQuery:

$.fn.mask = function(regex) { 
    this.on("keydown keyup", function(e) {
        if (regex.test(String.fromCharCode(e.which))) {
            return false;
        }
    });
}

It denies any input based on the regex you pass. Examples:

$("#textfield").mask(/\s/); // denies white spaces
$("#textfield").mask(/\D/); // denies anything but numbers

Those examples above works, but I'm trying to use a regex to accept numbers with decimal separator, like this:

$("#textfield").mask(/[^\d.,]/); // Anything except digits, dot and comma

That doesn't work. But if I log String.fromCharCode(e.which) on console when I press . or , it shows me these(respective) chars: ¾ and ¼.

The question is why String.fromCharCode(e.which) stands for those chars instead of the pressed ones?

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    The keycode you get from those events is a **key** code, not a character code. – Pointy Aug 14 '13 at 17:39
  • @Pointy Forgive my ignorance but I don't got the difference. – DontVoteMeDown Aug 14 '13 at 17:43
  • 4
    You are trying to get unicode characters from a key code, which only works in `keypress` handlers (not `keydown` or `keyup`). See [this question](http://stackoverflow.com/questions/1444477/keycode-and-charcode) for more info. – jbabey Aug 14 '13 at 17:43
  • The value identifies which key on the keyboard was pressed. Consider the "6" key - the code identifies the key, but that same key might result in a "6" or a "^". It's just a different concept. – Pointy Aug 14 '13 at 17:43
  • 1
    Following up on @Pointy's comment, [this answer](http://stackoverflow.com/a/5829387/901048) and [this one](http://stackoverflow.com/a/13127566/901048) might be helpful. – Blazemonger Aug 14 '13 at 17:45

1 Answers1

2

You want to deal with actual characters produced from keyboard, not a layout position of a key.

$.fn.mask = function(regex) { 
    this.on("keypress", function(e) {
        if (regex.test(String.fromCharCode(e.which))) {
            return false;
        }
    });
}

The keypress event reports the code point of a character produced.

http://jsfiddle.net/USgNJ/

Esailija
  • 138,174
  • 23
  • 272
  • 326