简体   繁体   中英

jQuery/Javascript - check if every element in a given array is within each of the others

I think I need some help with this. I'm sure there's an easy solution but I'm not getting it.

I have a search box in a page which automatically displays the FAQ questions which contain the search criteria as it is typed in.

Here's what I have at the moment:

var criteria = $('#search-criteria').val().toLowerCase().replace(/[^a-zA-Z 0-9]+/g," ");
$('.questions').each(function(){
        if ($(this).text().toLowerCase().match(criteria)) {
            $(this).attr('data-search','1');
        } else {
            $(this).attr('data-search','0');
        }
    });

It works, but the problem is it will only display questions which contain the search criteria consecutively ie word for word. I want to split each of these questions into an array and check that every word in the search criteria is SOMEWHERE in each question, enabling people to search for multiple keywords too rather than exact phrases.

I know that to turn each question into an array I need this:

$('.questions').each(function(){
        var questionSplit = $(this).text().toLowerCase().replace(/[^a-zA-Z 0-9]+/g," ").split(" ");
// if all of the parts in the criteria array are found in the given question 
//   {
//      $(this).attr('data-search','1');
//   } else {
//      $(this).attr('data-search','0');
//   }
// }

It's the last comparison bit I'm lacking. Any help appreciated!

Thanks

I have written this some time ago for an other project.

What about this:

$(table+" tbody td:MyCaseInsensitiveContains('"+val+"')").parent().show();

Where val is your search...

Sorry, I forgot -> You have to extend jquery like this:

$.extend($.expr[":"], {
"MyCaseInsensitiveContains": function(elem, i, match, array) {
    return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}

});

Then you can use :MyCaseInsensitiveContains as an pseudo-class for every element.

The trick with my example was: Show all content in a table. If user searches (variable val) hide all td`s and only show the ones with the text containing from the searchbox.

You can iterate though the search values like this:

$(this).attr('data-search','0');
for (var i = 0; i < questionSplit.length; i++) {
    if ($(this).text().toLowerCase().match(questionSplit[i])) {
        $(this).attr('data-search','1');
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM