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?
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!')
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With