When the page loads and user triggers an event, the javascript starts a getJSON query and fetches JSON string from the server. Its in form:
[{id:12,type:'car',title:'ferrari'}, {id:17,type:'bicycle',title:'ferrari'}]
So now I have this JSON string. Now I'm a bit stuck. So here's how I would want it to work:
In my page I have an input text search field in which user could type in letters and then javascript would automatically search results from this JSONstring, but only from titles. It should not search by type or by id. It should then return the result as JSON with all ID and types still there, which I could then pass to renderer which renders the results as li elements inside a ul element which is inside a div.
The part I'm having problems with is the actual search part. If I'd get the right results from search I know how to render them.
I have looked into autocomplete plugins but I cant get them to work like I want and they are not really intended for things like this I assume. I'd prefer most a plugin that is known to be safe and error free to use. If you are saying there is not a good plugin for this then I guess I'd would 开发者_开发问答have to do it myself. I just want to know before I start inventing a wheel again.
The reason for doing search on client side is that I think it will be less stress for server. The reason is that it starts with all results shown and since the results are already fetched I dont want to requery some of the results again. The reason why its fetched with ajax is because it wont be fetched unless user does a certain event, which would be a button click.
PS: If you have suggestions how you would do it with most efficient way, feel free to educate me :)
You'll have to loop through the array and match the title to the search query. You can match using substr() or using indexOf() or cook up something with Regex. Simply return the matches.
small code example:
function AutoComplete(searchquery, data){
var j = 0; var returns = [];
for(i in data){
if(data[i].title.indexOf(searchquery) > -1){ returns[j++] = data[i]; } }
return returns;
}
This should get you started, right?
PS: sorry, I didn't know how to format the code above.
function searchFromData(searchquery,data) {
var returns = [];
$.each(data,function(){
if(this.title.indexOf(searchquery) > -1){
returns.push(this);
}
});
return returns;
}
I used this function which is similar as post from daan.
精彩评论