views:

330

answers:

3

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?

+2  A: 

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

alxp
+8  A: 

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.

David
I usually prefer `re.test( $(this).text() )` as it returns a simple boolean
Már Örlygsson
Thanks, this gives me something to jump off
Cawlin
That's a good point, Már. I changed the answer to use re.test instead.
David
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.
Paolo Bergantino
Thanks, Paolo. This is what I get for writing out code without testing it. :)
David
+4  A: 

How about the quickSearch plugin?

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