Russell Parrott
Russell Parrott

Reputation: 903

JQuery search string by character

hope you can help,

I am trying to create a "simple" autocomplete/tag suggest type of function based on the value of an input field.

Example: User types "hello world" in the input field, what I want to do is on change match the charachters as they are typed against a list (predifined) so the list could be a <ul> or a <select> etc.

Prob. no need to go beyond the first 2 or 3 characters, in fact really just the first would do at the moment - so in example "hello world", the list might contain "hello world,hi world,help world,a world,another world, because world ...."

So if I type h as the first letter in my input all I would see in the <ul> or <select> list - placed after the input field so could use .next() is "hello world,hi world,help world".

Likewise if I typed a I would see "a world,another world". I hope clear? prob. is can't find any tutorials out there.

Thanks in advance

Upvotes: 2

Views: 4815

Answers (3)

karim79
karim79

Reputation: 342635

This is not difficult at all to create from scratch. Here is a partial solution I started working on a couple of weeks ago, you are welcome to it:

Markup:

<input type="text" />
<div id="results">
    <ul>
        <li>Cartman</li>
        <li>Snooker</li>
        <li>Star Wars</li>
        <li>Blue Velvet</li>  
    </ul>
</div>

$(document).ready(function() {
    $("#results").hide();
    $("input").keyup(function() {
        if (this.value.length) {
            var that = this;
            $("#results li").hide().filter(function() {
                return $(this).html().toLowerCase().indexOf(that.value.toLowerCase()) !== -1;
            }).show();
            $("#results").show();
        } else {
            $("#results").hide();
        }
    });
});

Try it out here.

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

The jquery auto complete plugin is what you are looking for.

Upvotes: 0

Michael Rivera
Michael Rivera

Reputation: 371

The jQuery UI Autocomplete widget supports autocompletes in a robust way. You will have to define a callback function to do the filtering, though, which is pretty easy.

If you click the "View source" on this particular demo, it shows how one can do filtering with a Regexp and the jQuery grep function.

This should get you started; what remains is to build that list from a jQuery selector on your <ul>'s child elements.

Upvotes: 1

Related Questions