I'm validating text-boxes such that they can contain letters,numbers, and these special characters only: ` , - . ' ~
I'm using the Jquery 'key-down' event for this. If the user enters an invalid character,I prevent it from showing up in the textbox. For the enabling just the tilde, and disabling the other special characters, I'm supposed to detect if the shift key is held down. I've used a Boolean variable for this.
Problem is it's allowing the other special characters like !, $, to be typed in.It isn't going inside the isShiftPressed == true condition in ValidateKeyDown . I had put an alert inside it, which didn't execute.
So this is my code:
$.fn.ValidateKeyDown = function () {
return this.each(function () {
$(this).keydown(function (e) {
if (e.shiftKey) {
isShiftPressed = true;
return;
}
else if (isShiftPressed == false) {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 9) // Tab
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 65 && n <= 90) // alphabets
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105) // number on keypad
|| (n == 109) //(- on Num keys)
|| (n == 189) || (n == 190) || (n == 222) || (n == 192) //hypen,period,apostrophe,backtick
)
) {
e.preventDefault(); // Prevent character input
return false;
}
}
else if (isShiftPressed == true) {
var n = e.keyCode;
if (n != 192) {
e.preventDefault(); // Prevent character input
return false;
}
}
return true;
});
});
};
$.fn.ValidateKeyUp = function () {
return this.each(function () {
$(this).keyup(function (e) {
if (e.shiftKey) {
isShiftPressed = false;
}
});
});
};
isShiftPressedbetween key strokes. Try puttingvar isShiftPressed = false;outside of the functions to declare it globally.