Andrew
Andrew

Reputation: 25

How to filter search results based on multiple data attributes

I'm trying to search multiple data results based on inline data attributes. However, I can only figure out how to search a single data attribute instead of them all. How would I accomplish this?

What I have: http://jsfiddle.net/9SMZC/2/

$("input[type=text]").keyup(function () {
    var filter = $(this).val();

    $("a").each(function () {
        if ($(this).attr("data-event-name").search(new RegExp(filter, "i")) < 0) {
            $(this).hide();
        } else {
            $(this).show();
            matches++;
        }
    });
});

Thanks in Advance!

Upvotes: 1

Views: 1837

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

If you want to apply a "or" logic, you may do this :

$("input[type=text]").keyup(function () {
    var filter = $(this).val();
    $("a").each(function () {
        var data = $(this).data();
        $(this).hide();
        for (var key in data) {
            if (~data[key].search(new RegExp(filter, "i"))) {
                $(this).show();
                break;
            }
        }
    });
});

Demonstration (try to search "andrew" for example)

The idea is to get the data object and iterate over the properties. To simplify the code (that is to avoid keeping a boolean) I also always hide and show when the element is ok.

Upvotes: 3

Related Questions