How to fix search in <li> where users can use caps or lowercase letters?
Below is the JavaScript I am using for my search query, there is an error I found, a problem with a letter that is a header or a lowercase letter. If the letters in the list are lowercase then it only searches lowercase, but if you had to rotate the caps it won't find anything. Below are the codes where I use any help would be appreciated.
Html
<input type='search' id='search' placeholder='search'>
<ul>
<li>example 1</li>
<li>example 2</li>
<li>example 3</li>
</ul>
JavaScript
var search = $("#search");
var listItems = $("li");
search.on("keyup", function () {
var terms = search.val();
if (terms == '') {
listItems.show();
} else {
listItems.hide();
$("li:contains('" + terms + "')").show();
}
});
+3
source to share
3 answers
You can overwrite existing jquery contains
:
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
var search = $("#search");
var listItems = $("li");
search.on("keyup", function () {
var terms = search.val();
if (terms == '') {
listItems.show();
} else {
listItems.hide();
$("li:contains('" + terms + "')").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='search' id='search' placeholder='search'>
<ul>
<li>example 1</li>
<li>example 2</li>
<li>example 3</li>
</ul>
Or create a new one:
jQuery.expr[':'].ncontains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
var search = $("#search");
var listItems = $("li");
search.on("keyup", function () {
var terms = search.val();
if (terms == '') {
listItems.show();
} else {
listItems.hide();
$("li:ncontains('" + terms + "')").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='search' id='search' placeholder='search'>
<ul>
<li>example 1</li>
<li>example 2</li>
<li>example 3</li>
</ul>
+2
source to share
You can use toLowerCase :
//elsewhere case may vary but here only case is ignored
$("li:contains('" + terms.toLowerCase() + "')").show();
While you are considering using this elsewhere in your code:
//elsewhere case is ignored by transforming lowercase terms to search for
var terms = search.val().toLowerCase();
+2
source to share