I'm having some trouble with checking if a value is not in an array. I'm trying to allow only certain key presses in a textbox.
Here's what I have:
var keyCodeArr = [ 8,9,13,17,18,37,39,46 ];
$('#txtSearch').keydown(function(event) {
var code = event.keyCode;
if (!$.inArray(code,keyCodeArr)) {
event.preventDefault();
}
});
It's allowing anything in the textbox. I looked at the documentation for $.inArray(), which show an example for seeing if a value is in an array, so I thought just adding the NOT in front of it would do the trick.
Or is it that I'm not initializing the array correctly in the first place?
What am I missing?
hakre
199k55 gold badges453 silver badges865 bronze badges
asked Jan 21, 2013 at 18:01
1 Answer 1
Using jquery:
if (!~$.inArray(code,keyCodeArr)) {
...
}
answered Jan 21, 2013 at 18:03
Sign up to request clarification or add additional context in comments.
1 Comment
marky
Thanks, roasted for the code and adeneo and Peter for pointing out to me that I didn't read the docs close enough!
lang-js
event.which
is normalized in jQuery.I looked at the documentation for $.inArray()
and I see if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.