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?
I have had some help on a Jquery script which creates a searchable, toggleable FAQ. The code can be seen here:
http://jsfiddle/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?
Share Improve this question asked Jul 30, 2012 at 10:15 J.ZilJ.Zil 2,4498 gold badges46 silver badges82 bronze badges 2- css-tricks./snippets/jquery/… – Pavel Staselun Commented Jul 30, 2012 at 10:19
- stackoverflow./questions/5619102/… – Jith Commented Jul 30, 2012 at 10:20
3 Answers
Reset to default 6Update
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();
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();
}
});
// 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();
}
});
}