Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a value to JSON array values in jquery

Tags:

json

jquery

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?

like image 976
chrism Avatar asked May 14 '10 14:05

chrism


2 Answers

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!')
}
like image 98
Atanas Korchev Avatar answered Sep 19 '22 15:09

Atanas Korchev


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.

like image 44
Matt Avatar answered Sep 22 '22 15:09

Matt