Kyle Kyle - 21 days ago 7
Ajax Question

Use AJAX or similar technology to narrow down already existing list

Hopefully I explain this to where it makes sense, the most I could find by searching terms like I used in the title gave plenty of autocomplete examples, but nothing quite what I'm looking for. I have a list of buttons (they're coded as inputs right now) and I want to add a search field that will narrow down the buttons as the user types in a search field.

Say for example, I have 30 buttons with popular websites. If a person wanted to pull Google, they'd start typing it out which would start by including everything with the letter "G" in it, then "O", etc. Everything else would "disappear" from the page.

I can sort of think of a way to do this manually, but I think my code wouldn't be DRY. Possibly set an "on" and "off" ID, and use CSS to display:none or something to that effect.

I think the best way to do this would be via AJAX, but there may be some javascript voodoo more applicable.

Answer

To easy. At first, its unneccessary to filter the answers serverside, if all the data is already at the users. Also, you shouldnt write html and filter it with js, you should write it in js and generate an html output. Lets start with the structure:

var links=[
  {
       name:"google",
       url:"http://google.com"
   },
   {nextone}
   ];

Now generate the links in html:

window.onload=function(){
    var container=document.body;//change this to your needs
  for(i=0;i<links.length;i++){
     var link=links[i];
     link.html=document.createElement("a");
     link.html.innerHTML=link.name;
     link.html.src=link.url;
     container.appendChild(link.html);
 }
 };

If sth is inputed, hide the the unmatched ones:

function filter(string){
 //loop trough links
 for(i=0;i<links.length;i++){
    var link=links[i];
    //if string doesnt match name
    if(!link.name.split(string)[1]){
       link.html.style.display="none";
     }else{
       link.html.style.display="block";
     }
  }
  }

Use like this:

filter("goo");

You could bind that to an input:

yourinput.addEventListener("onchange",function(){filter(this.value)},false);