I'm using a simple input field to search through a list on my website using this code:
$('#f-search').keyup(function() {
var q = $('#f-search').val().toLowerCase();
$("#f-list .f // toLowerCase // :contains('q')").css('border-color', '#900');
});
My problem is that the list elements ( .f
) contain unpredictable capital letters, so in order to accurately check it against the input I need to convert it to lower case, but I don't know how to do that and then use :contains
. For example, if one .f
contains "WoWoWoWoWzzzziees" but the user typed "wow", it wouldn't be a match with my current code, but I'd like it to be.
What you want is:
$("#f-list .f").filter(function() {
return $(this)
.text() // or .html() or .val(), depends on the element type
.toLowerCase()
.indexOf(q) != -1;
}).css('border-color', '#900');
which compares the text inside your elements selected by "#f-list .f"
and, if they contain what is in the q
variable, they get the css modification applied.
EDIT:
If you also want the list to be reset each time, you can do this:
$("#f-list .f").css('border-color', 'WHATEVER IT WAS').filter(function() {
return $(this)
.text() // or .html() or .val(), depends on the element type
.toLowerCase()
.indexOf(q) != -1;
}).css('border-color', '#900');
For better performance you could cache your list like this:
var f_list = $("#f-list .f"),
f_search = $('#f-search');
f_search.keyup(function() {
var q = f_search.val().toLowerCase();
f_list.css('border-color', 'WHATEVER IT WAS').filter(function() {
return $(this)
.text() // or .html() or .val(), depends on the element type
.toLowerCase()
.indexOf(q) != -1;
}).css('border-color', '#900');
});
You can go as far as creating your own custom :contains
selector in jQuery:
jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
And use it like this (please note the new selector is :Contains
with uppercase C):
$("#f-list .f:Contains('q')").css('border-color', '#900');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.