wilsonpage
wilsonpage

Reputation: 17610

Suggestive Search From JS Array, Possible?

Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.

So imagine a javascript object or array that is full of people's names:

var array = (jack,tom,john,sarah,barry,...etc);

I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.

I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.

Hope someone can help me with this!

W.

Upvotes: 0

Views: 280

Answers (3)

wilsonpage
wilsonpage

Reputation: 17610

I ended up using the following function to build my AJAX free instant search bar:

Example JS object being searched:

var $members = {
  "123":{firstname:"wilson", lastname:"page", email:"[email protected]"},
  "124":{firstname:"jamie", lastname:"wright", email:"[email protected]"}
}

Example of function to search JS object:

$membersTab.find('.searchWrap input').keyup(function(){
      var   $term       = $(this).val(),
            $faces      = $membersTab.find('.member'),
            $matches    = [];

      if($term.length > 0){
        $faces.hide();
        $.each($members,function(uID,details){ 
          $.each(details,function(detail,value){
            if(value.indexOf($term) === 0){//if string matches term and starts at the first character
              $faces.filter('[uID='+uID+']').show();
            } 
          });  
        });
      }else{
        $faces.show();  
      }

});

It shows and hides users in a list if they partially match the entered search term.

Hope this helps someone out as I was clueless as to how to do this at first!

W.

Upvotes: 0

user187291
user187291

Reputation: 53950

as the name suggests, this finds elements of an array starting with the given string s.

Array.prototype.findElementsStartingWith = function(s) {
   var r = [];
   for(var i = 0; i < this.length; i++)
      if(this[i].toString().indexOf(s) === 0)
         r.push(this[i]);
   return r;
}

// example

a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))

the rest is basically the same as in ajax-based scripts.

Upvotes: 1

shamittomar
shamittomar

Reputation: 46702

http://wwwo.google.com?q=autosuggest+using+javascript

AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.

Upvotes: 1

Related Questions