开发者

Jquery/Javascript regex: filter, allow multiple tags to be typed in to select that category, jsfiddle

http://jsfiddle.net/nicktheandroid/AtkNW/

The goal is to take the value of an textbox, which will have multiple keywords in it seperated by a space, then filter the list to show the item(s) that contain all of those keywords. Right now, I can only type those keywords in as they are listed in <span class="tags">.

I would like to be able to type them in, but out of order, and have it still only keep the item with all those keywords as the visible item. I think I might have to use .split(" ") somewhere in here... hmm...

<li>entertainment
    <span class="tags">tv radio dance opera</span>   开发者_如何转开发   
</li>

Jquery:

$("#filter").keyup(function () {
    var filter = $(this).val(), count = 0;
    var length = $(this).val().length;
    if (length > 1) {
        $(".filtered li").each(function () {
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).addClass("hidden");
            } else {
                $(this).removeClass("hidden");
                count++;
            }
        });
    } else {
        $('.filtered li').removeClass("hidden")
            count++;
    }
    $("#filter-count").text(count);
});

would anyone know how to accomplish this?


Exactly as you suspected, you'll need to use String.split() to split the user input, and match the words one-by-one against your tags.

Modified code as:

$("#filter").keyup(function() {
    var filter = $(this).val(),
        count = 0;
    var length = $(this).val().length;
    if (length > 1) {
        var filter_tags = filter.split(" "); // Split user input by spaces
        $(".filtered li").each(function() {
            var $this = $(this);
            var matches = true;
            // Match each splitted string against the whole tags string
            $.each(filter_tags, function(i, a_filter) {  
                if ($this.text().indexOf(a_filter) === -1) {
                    matches = false;
                }
            });
            if (matches) {
                $this.removeClass("hidden");
                count++;
            } else {
                $this.addClass("hidden");
            }
        });        
    } else {
        $('.filtered li').removeClass("hidden")
        count++;
    }

    $("#filter-count").text(count);
});

You might need to pass a smart regexp to the split to allow both for spaces and commas as separators.

Working example at http://jsfiddle.net/AtkNW/31/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜