Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event key code for ampersand?

I am trying to find the keycode for ampersand and underscore. I should not allow my users to allow to enter ampersands and underscores. I was taking a look at one list, and it mentions 55 as the keycode for both 7 & ampersand, and another list says that 55 is the keycode for 7. So if I return false when my user hits the keycode 55, I am disallowing the user from using 7, which isn't the requirement. How do I find the keycodes for ampersand and underscore?

I just tried with 55, but it only is giving me the alert 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;
    }
}
like image 856
sai Avatar asked Jul 20 '10 15:07

sai


2 Answers

Use the keypress event and test directly for the character as follows. Don't mess with key codes: they will vary between different keyboard types and cultures. Character codes won't.

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;
    }
};
like image 97
Tim Down Avatar answered Sep 22 '22 05:09

Tim Down


Check if the shift key is down:

//e = Event
(e.shiftKey && e.keyCode === 55) //returns true if Shift-7 is pressed
like image 38
tcooc Avatar answered Sep 21 '22 05:09

tcooc