J.Zil
J.Zil

Reputation: 2449

Searching with Jquery - Work for multiple terms

I found this great snippet online for a searchable FAQ. However, I was wondering if anyone knew how it could be modified to work with multiple terms.

http://jsfiddle.net/pT6dB/

On the example above, I would like to be enter "paper Earth" to have both example results returned. If I enter that now, it doesn't return anything. I guess I want to make it equivalent to searching "paper" OR "Earth".

Any help would be much appreciated.

James

Upvotes: 0

Views: 3369

Answers (2)

Shawn Aukstak
Shawn Aukstak

Reputation: 806

You need to split the value by the " " character using the javascript string.split function. Then loop through each element to see if there is a match.

For example:

 $('#search').keyup(function(e) {
        var s = $(this).val().trim();
        if (s === '') {
            $('#result LI').show();
            return true;
        }

        $('#result LI').hide();

        splits = s.split(" ");

        for(x in splits){
            $('#result LI:contains(' + splits[x]+ ')').show();
        }

        return true;
    });

Upvotes: 3

pimvdb
pimvdb

Reputation: 154918

What you can do is matching the search string against a regular expression to get all words. Then, for each li you check whether its text contains any of the words and show or hide appropriately. I've used array.some which is only available on newer browsers, though.

I've tidied it up a bit as well - not all code was necessary: http://jsfiddle.net/pT6dB/29/.

// no need for preventDefault here - clicking a <strong> doesn't do anything
$('li strong').click(function(e) {
    $(this).parent().find('em').slideToggle();
});

// the "input" event is available on newer browsers, and is also fired when e.g.
// pasting or dragging text
$('#search').on("input", function(e) {
    // make it case-insensitive, and match against a regexp that matches
    // non-space characters
    var words = $(this).val().toLowerCase().match(/\S+/g);
    if (!words) {  // no match, i.e. no words found
        $('#result li').show();
    } else {
        $('#result li').each(function() {
            var text = $(this).text().toLowerCase();
            var show = words.some(function(word) {
                return ~text.indexOf(word);  // ~ with indexOf means "contains"
            });
            $(this).toggle(show);  // will show or hide depending on "show"
        });
    }
});

Upvotes: 3

Related Questions