tags:

views:

162

answers:

4

I have a JSON array that looks like this:

['Monkey','Cheetah','Elephant','Lizard','Spider']

I also have a text input. I want to test whether the value of the input upon 'blur' is also in the array and if it is do something.

Knowing a bit of python I tried something like this:

var existing_animals = ['Monkey','Cheetah','Elephant','Lizard','Spider']
$('input').blur(function() {
  user_animal = $(this).val()
  if (user_animal in existing_animals) {
    alert('Animal already exists!')
  }
});

So, how rookie is my mistake?

A: 

If you want to use the "in" keyword in JS, this might be helpful: http://stackoverflow.com/questions/2630364/reduce-multiple-ors-in-if-statement-in-javascript/

Ed
A: 

I believe you might find your answer in this article.

Since the JSON evaluates to an array, you should be looking at the indexOf function. Not sure why you mentioned python here..

Jeriko
+4  A: 

The in operator checks if a key is present in a dictionary (object). It however does now work for arrays. The right approach is to use jQuery.inArray:

if ($.inArray(user_animal, existing) > -1) {
    alert('Animal already exists!')
}
korchev
I knew I use jQuery for a reason, while the other answers may be right, this is simple enough even for me, thanks
chrism
+3  A: 

in is for checking if an object includes the attribute, where-as you're using an array.

If you want to use your in, you can do:

var existing_animals = {
  "Monkey":1,
  "Cheetah":1
};

etc, then all will be fine using in, however, it would be better to continue using your Array, and simply loop over it.

$('input').blur(function() {
  user_animal = $(this).val()

  for (var i=0;i<existing_animals.length;i++) {
     if (existing_animals[i] == user_animal) {
        alert("Animal exists");

        break;
     };
  };
});

The ECMA 5th edition introduces an indexOf method for Arrays, so it should be as easy as doing:

if (existing_animals.indexOf(user_animal) != -1) {
   alert("Animal exists");
};

However, IE doesn't support this; you can implement it yourself though.

Matt
I just used 'in' because it's a concept I use when writing python
chrism
Sure, I was just giving an idea of how `in` works :)
Matt