-2

How can I make input box for name only allow both E and non-E character, not special character on keydown event.

For example: Accept: a â è ㅎ 啊 Deny: . \ | } ) # +

And also I don't know why:

'.'.charCodeAt(0) = 46 (chrome console)

In my keydown event if I type dot (.)

 e.which = 190

if I type dot (.) in numlock keyboard

e.which = 110

so confuse.

chiquyet
  • 527
  • 4
  • 14
  • 1
    Is keydown a requirement? Otherwise use keypress event – A. Wolff Nov 26 '15 at 08:27
  • What you got is the KEYCODE 110 = decimal Point; 190 = period. It's a different key that was pressed. What you need is the resulting CHARACTER. Especially the key "decimal point" on your numpad will be a different character on different systems, depending on the locale you work on. As A. Wolff suggests, the event keypress() returns the actual resulting character while keydown() returns the keycode of the key pressed. – Fuzzzzel Nov 26 '15 at 08:40

2 Answers2

1

Try this. Seems it works fine with jQuery 1.4.2, FF, IE, Chrome.

<script>
    $("input").keypress(function (e) {
        if (e.which !== 0 &&
            !e.ctrlKey && !e.metaKey && !e.altKey) {
            alert(String.fromCharCode(e.which));
        }
    });
</script>
Anju Aravind
  • 3,262
  • 2
  • 16
  • 22
0

You can use this regex to replace all special characters from String :

String.replace(/[\u0021-\u002e\u003a-\u0040\u005b-\u0060\u007b-\u007e]*/g, "")

Similarly you can use this regex to find if user's entered text matches the regex and return false.

akgaur
  • 755
  • 1
  • 6
  • 21
  • Actually I want some special characters also accepted. And notice that I want to implement it on keydown event. If I use String.fromCharCode() to convert keycode to character. Sometime it's goes wrong. Like: If I type 5 on numlock keyboard, keycode will be 101 But String.fromCharCode(101) = 'e' – chiquyet Nov 27 '15 at 02:54