Take two :) I have a jquery's autocomplete texbox and, upon a click of a button, I need to check if the value entered has come from the autocomplete or is it a completely new value.
The problems is that 'cache' is some sort of an array of JSON objects, but to be able to use if ( input in cache ) { ... } I need to convert it to a simple javascript array. What would be the best way to do that?
P.S. FireBug says 'cache=[object Object]'
//////////////////////////////////////////// autocomplete code //////////////////
var cache = {},
lastXhr;
$( "#inputV" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
////////////////////////// check if input comes from autocomplete //////////////////
$('#btn_check').click(function() {
var input = $("#inputV").val();
alert(input);
console.log('cache='+cache);
/// FireBug says 'cache=[object Object]'
if ( input in cache )
{
alert("yes");
}
else
{
alert("no");
}
});
Here's that a response looks like.
[
{
"id": "Podiceps nigricollis",
"label": "Black-necked Grebe",
"value": "Black-necked Grebe"
},
{
"id": "Nycticorax nycticorax",
"label": "Black-crowned Night Heron",
"value": "Black-crowned Night Heron"
},
{
"id": "Tetrao tetrix",
"label": "Black Grouse",
"value": "Black Grouse"
},
{
"id": "Limosa limosa",
"label": "Black-tailed Godwit",
"value": "Black-tailed Godwit"
},
{
"id": "Chlidonias niger",
"label": "Black Tern",
"value": "Black Tern"
},
{
"id": "Larus marinus",
"label": "Great Black-backed Gull",
"value": "Great Black-backed Gull"
},
{
"id": "Larus fuscus",
"label": "Lesser Black-backed Gull",
"value": "Lesser Black-backed Gull"
},
{
"id": "Larus ridibundus",
"label": "Black-headed Gull",
"value": "Black-headed Gull"
},
{
"id": "Turdus merula",
"label": "Common Blackbird",
"value": "Common Blackbird"
},
{
"id": "Sylvia atricapilla",
"label": "Blackcap",
"value": "Blackcap"
},
{
"id": "Rissa tridactyla",
"label": "Black-legged Kittiwake",
"value": "Black-legged Kittiwake"
},
{
"id": "Aegypius monachus",
"label": "Eurasian Black Vulture",
"value": "Eurasian Black Vulture"
}
]
var cache = {}. I don't understand your problem... You should provide an example ofcacheand what you want to transform it into. I thinkif ( input in cache )will work fine.inoperator. It does not test whether an element is in an array, it tests whether a property is set on an object: developer.mozilla.org/en/JavaScript/Reference/Operators/Special/… . If you use it with an array, you test whether a particular index is set.