I'd like to restrict keys that can be pressed.
$('.txtComments').keydown(function (event) {
var keys = new Array();
keys[0] = "8";
keys[1] = "46";
keys[2] = "37"
keys[3] = "39"
if(!(....)) //Check whether the keyCode is either of 8, 46, 37, or 39.
{
event.preventDefault();
}
});
Thanks for helping
Answer
There are so many ways to implement this:
Just hard code it:
var keyCode = event.which;
if (keyCode != 8 && keyCode != 46 ...)
or check an array:
var keys = [8, 46, ...];
if (keys.indexOf(keyCode) < 0)
or the jQuery equivalent:
if ($.inArray(keyCode, keys) < 0)
or check an object:
var keys = { 8: 1, 46: 1, ... }
if (! (keyCode in keys) ) // or if (!keys[keyCode])
or a switch:
switch (keyCode) {
case 8: case 46: ...
// do nothing
break;
default:
event.preventDefault();
}
No comments:
Post a Comment