Ampersand key code event?

I am trying to find keycode for ampersand and underscore. I should not allow my users to enter ampersands and underscores. I looked at one list and it mentions 55 as the key code for 7 and ampersands, and the other list says 55 is the key code for 7. Therefore, if I return false when my user types 55, I deny the user can use 7, which is not a requirement. How to find keycodes for ampersand and underline?

I just tried with 55, but that only gives me a warning for 7 not with ampersand!

function noenter(e)
{
    evt = e || window.event;
    var keyPressed = evt.which || evt.keyCode;

    if(keyPressed==13)
    {
        return false;
    }
    else if(evt.shiftKey && keyPressed===55)
//  else if(keyPressed==59 || keyPressed==38 || keyPressed==58 || keyPressed==95)
    {
        alert("no special characters");
        return false;
    }
}
+5
source share
4 answers

keypress . : . .

var el = document.getElementById("your_input");

el.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    var charStr = String.fromCharCode(charCode);
    if (charStr == "&" || charStr == "_") {
        alert(charStr);
        return false;
    }
};
+8

, shift:

//e = Event
(e.shiftKey && e.keyCode === 55) //returns true if Shift-7 is pressed
+2

OK it turned out! it's 38! Sorry for raising this question!

0
source

I solved this using the Unicode key id. Below is my implementation using jQuery:

function parseKey(key) {
    return parseInt(key.substring(2), 10);
}

$inputs.bind('keydown', function(e) {
    var c=parseKey(e.originalEvent.keyIdentifier);
    //allow only numbers and backspace
    if ((c<30 || c>39) && e.which!=8)
        e.preventDefault();
    if (e.which == 13)
        $(this).blur();
});
0
source

All Articles