1

I have had some help on a Jquery script which creates a searchable, toggleable FAQ. The code can be seen here:

http://jsfiddle.net/pT6dB/62/

The trouble is, if there is the word “How” with an upper case “H” and I search “h”, it wont find it. How can I make this script case insensitive?

J.Zil
  • 2,397
  • 7
  • 44
  • 78

3 Answers3

6

Update

Alternatively, you could reduce the amount of code significantly using regular expression. jsFiddle demo

$('#search').keyup(function(e) {
    // create the regular expression
    var regEx = new RegExp($.map($(this).val().trim().split(' '), function(v) {
            return '(?=.*?' + v + ')';
        }).join(''), 'i');

    // select all list items, hide and filter by the regex then show
    $('#result li').hide().filter(function() {
        return regEx.exec($(this).text());
    }).show();
});​

Original

Based on your current algorithm for determining relative elements, you could use the jQuery filter method to filter your results based on the keywords array. Here's a rough idea:

// select the keywords as an array of lower case strings
var keywords = $(this).val().trim().toLowerCase().split(' ');

// select all list items, hide and filter then show
$('#result li').hide().filter(function() {
    // get the lower case text for the list element
    var text = $(this).text().toLowerCase();        

    // determine if any keyword matches, return true on first success
    for (var i = 0; i < keywords.length; i++) {
        if (text.indexOf(keywords[i]) >= 0) {
            return true;
        }
    }
}).show();
Richard
  • 8,110
  • 3
  • 36
  • 59
  • That is really interesting, but you're demo doesn't seem to work in the same way – J.Zil Jul 30 '12 at 11:27
  • the problem is if someone types "is" it returns all the results. Its better I think if someone searches "oh hello" to search for results which only contain "oh" AND "hello", instead of "oh" OR "hello" – J.Zil Jul 30 '12 at 11:31
  • My apologises @JamesWillson, this should now work as an 'AND' rather than an 'OR'. – Richard Jul 30 '12 at 15:10
  • I came here to vote on this again, that you @Richard – lharby Apr 11 '17 at 08:43
1

Change this line

$('#result LI:not(:contains('+keywords[i]+'))').hide();

to

$('#result LI').each(function()
{
    if(this.innerHTML.toLowerCase().indexOf(keywords[i].toLowerCase()) === -1)
    {
        $(this).hide();
    }
});
Summoner
  • 1,397
  • 1
  • 9
  • 9
1
// split the search into words
var keywords = s.toLowerCase().split(' ');

// loop over the keywords and if it's not in a LI, hide it
for(var i=0; i<keywords.length; i++) {
    $('#result LI').each(function (index, element) {
        if ($(element).text().toLowerCase().indexOf(keywords) != -1) {
            $(element).show();
        } else {
            $(element).hide();
        }
    });
}
M. Mennan Kara
  • 10,072
  • 2
  • 35
  • 39