2

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
2
  • The docs says to check for -1 values, and event.which is normalized in jQuery. Commented Jan 21, 2013 at 18:04
  • 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. Commented Jan 21, 2013 at 18:04

1 Answer 1

7

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

Thanks, roasted for the code and adeneo and Peter for pointing out to me that I didn't read the docs close enough!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.