开发者

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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜