Thursday, March 24, 2011

Narrow a list of items as you type with javascript

I am trying to find a plugin or a solid way to narrow a list of items as a user types.

Essentially there would be a list that is always visible containing product names for users to scroll through. At the bottom would be a form where you can type in the name of a product. As you type the list is narrowed down.

I have been trying to find a way to adapt something like jQuery UI's autocomplete to work in this way but having some trouble.

Anyone created something like this before or have any ideas?

From stackoverflow
  • Code to filter a table of data can be found here. Also includes a live demo.

  • Here's a quick example of an approach that can work:

    HTML:

    <ul id="products">
        <li>Apple</li>
        <li>Banana</li>
        <li>Mango</li>
    </ul>
    <input id="filter" />
    

    JS:

    var $products = $('#products li');
    $('#filter').keyup(function() {
        var re = new RegExp($(this).val(), "i"); // "i" means it's case-insensitive
        $products.show().filter(function() {
            return !re.test($(this).text());
        }).hide();
    });
    

    That's a simple approach, and would probably need a bit of tweaking. But it's close to what you need.

    Már Örlygsson : I usually prefer `re.test( $(this).text() )` as it returns a simple boolean
    Cawlin : Thanks, this gives me something to jump off
    David : That's a good point, Már. I changed the answer to use re.test instead.
    Paolo Bergantino : The code above has a small but important error. The first line of the javascript should read: var $products = $('#products li'); - without the li $(this).text() inside the filter is a string with all the li elements concatenated.
    David : Thanks, Paolo. This is what I get for writing out code without testing it. :)
  • How about the quickSearch plugin?

    Cawlin : This is perfect, thanks!
    Nick Pierpoint : It's a great plugin for a static list.
    thebrokencube : So awesome for this task. Turned what I thought would take quite some time into a 10 minute ordeal. Thanks!

0 comments:

Post a Comment