Reputation: 5784
I have a code for filtering my searchresults using 2 inputs. I am using jquery for this.
<script>
$(document).ready(function () {
$(".search").keyup(function () {
$(".searchli").hide();
if ($("#refine").val() != "") {
var term = $("#search").val() + " " + $("#refine").val();
} else {
var term = $("#search").val();
}
$("li:contains('" + term + "')").show();
});
});
</script>
Search: <input type="search" id="search" class="search" length="24" />
Refine <input type="search" id="refine" class="search" length="24" />
My list with results contain Uppercases and Lowercases. My problem is that I can't search in lowercases (type keywords in lowercase) It can't find any results then.
How can I add toLowerCase()
or toUpperCase()
to my code so it will work?
Upvotes: 1
Views: 1152
Reputation: 6517
You can override the jQuery contains selector to ignore case using this snippet found on this page:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Alternatively you could create a new selector instead of overriding :contains (which could theoretically cause weird behaviour in other scripts) by calling it :containsInvariant or something.
EDIT: This wasn't compatible with all versions of jQuery, so here's one that should work across all versions:
// An implementation of a case-insensitive contains pseudo
// made for all versions of jQuery
(function( $ ) {
function icontains( elem, text ) {
return (
elem.textContent ||
elem.innerText ||
$( elem ).text() ||
""
).toLowerCase().indexOf( (text || "").toLowerCase() ) > -1;
}
$.expr[':'].icontains = $.expr.createPseudo ?
$.expr.createPseudo(function( text ) {
return function( elem ) {
return icontains( elem, text );
};
}) :
function( elem, i, match ) {
return icontains( elem, match[3] );
};
})( jQuery );
Upvotes: 1
Reputation: 6764
Use this to patch the Contains function to be case insensive...
Edit - Here's the code
// NEW selector
jQuery.expr[':'].Contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
JQuery 1.8 version
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Upvotes: 0