Tuesday, 19 September 2017

javascript - How to check whether an array contains an element




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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...