PHP/Javascript - Instant search, but different?

1.9k views Asked by At

I have a page with a blank search bar, and then a bunch on contacts below it in a table. Each contact is one div.

I want to be able to filter the contact table as text is entered into the search bar. (So, for instance, if "Fran" was typed in to the search bar, you'd only see contacts with "Fran" in their name. And then all would go back to default if "Fran" was deleted.)

Is this possible? How? (I found an instant search diy guide, but it only worked the way Google does, with a dropdown beneath the search bar.)

4

There are 4 answers

0
Daveo On

Here is some example Javascript for you:

<script type="text/javascript">
$(document).ready(function() {
    $("#search").keyup(function() {
        // Get the search value
        var searchValue = $(this).val();

        // If no value exists then show all divs
        if(searchValue === "") {
            $(".your_div").show();
            return;
        }

        // Initially hide all divs
        $(".your_div").hide();

        // Now show any that contain the search value
        $(".your_div:contains('" + searchValue + "').show();
    }); 
}); 
</script>
0
jondavidjohn On

I would suggest using this jquery plugin, it requires no ajax or server communication, it simply filters a rendered table according to an input box contents at every keystroke.

Make sure to also include the jquery library in your project along with this plugin for this to work.

1
Clyde Lobo On

You can try jQuery auto complete plugin for the same

0
shadylane On

The following contains the basic logic you need although it's the reverse - it hides content that it finds and only for exact matches. Also, it's an on keypress event so it only hides the divs after you hit space after typing the name so you'll need to tweak that too. To look for matches within a long string of text, you will need to use some regex to test against the search string.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Search</title>
    <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
    <script>            
        $(document).ready(function(){
                $(".searchbox").keypress(function(){
                      $("div").each(function(){
                    if($(this).text() == $(".searchbox").val()){
                        $(this).hide("fast");
                    };
                      });
                });
            });
    </script>
    </head>
    <body>
    <form><input type="text" class="searchbox"></form>
        <div>Susan</div>
        <div>Fran</div>
        <div>Dave</div>
    </body>
    </head>
</html>