Reputation: 2449
I have had some help on a Jquery script which creates a searchable, toggleable FAQ. The code can be seen here:
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?
Upvotes: 1
Views: 9100
Reputation: 8280
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();
});
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();
Upvotes: 6
Reputation: 10222
// 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();
}
});
}
Upvotes: 1
Reputation: 1407
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();
}
});
Upvotes: 1