Reputation: 55
Below is JavaScript I'm using for search query there is bug i have found which is issue with letter being caps or lower case. If the letters in list are lower case then it only searches for lower case but if you were to turn the caps on it doesn't find anything. Below are the codes i'm using any help will 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();
}
});
Upvotes: 3
Views: 79
Reputation: 85573
You may use toLowerCase:
//elsewhere case may vary but here only case is ignored
$("li:contains('" + terms.toLowerCase() + "')").show();
While you consider using this elsewhere in your code:
//elsewhere case is ignored by transforming lowercase terms to search for
var terms = search.val().toLowerCase();
Upvotes: 2
Reputation: 33218
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>
Upvotes: 2
Reputation: 33409
You can make the terms
lowercase and then search.
var terms = search.val().toLowerCase();
Upvotes: 3