views:

284

answers:

2

Hey, I am trying to create a search field that will filter or show/hide(which ever is best) the list elements based on what the user typed in and clicked the search button. I have no idea how to do this. everything I tried does not work unfortunately and im unsure of the best approach for this, like do i use show and hide or is there something better?

This is my HTML:

<html>
    <head>

    </head>
    <body>
    <label for="filter">Filter</label>  
    <input type="text" name="filter" value="" id="filter" />

        <a id="addtag" href="#">Search</a> 

    <ul>
        <li id="Hero1">Superman</li>
        <li id="Hero2">Batman</li>
        <li id="Hero3">Spiderman</li>
        <li id="Hero4">Iron Man</li>
        <li id="Hero5">The Hulk</li>
    </ul>

    </body>
</html>

So, if someone types in 'Superman' and clicks the search button, then only the Superman list element will be displayed.

Any help on this would be great. Thanks.

+3  A: 

You might be better off using a jQuery Search Plugin, like this one.

Robert Harvey
I don't like the keyup method. I want to push the search button and have results will display based on the entire string inputted.
Spyderfusion02
Man, do some looking around on Google. "Live" searches exist and I'm sure you can find something that gets around your keyup issue; either that or you'll find something you can modify to suite your needs.
jeerose
Just hook the click method of the button in the plugin's code instead of the keyup method in the search text box. That said, users really like this collapsible behavior, and it works for hundreds of rows.
Robert Harvey
+1  A: 

Very basic version, but no need of plugins and it works:

$("#addtag").click(function(){
  $("ul li").hide()
  .filter(":contains('"+ $("#filter").val() +"')").show()
  return false;
})
duckyflip
+1 I just tried it, and it does indeed work (although the matching is case-sensitive).
Robert Harvey