2

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.

user2250471
  • 1,002
  • 3
  • 10
  • 23

2 Answers2

3

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');
});
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
1

You can go as far as creating your own custom :contains selector in jQuery:

From here and here and here:

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');
Community
  • 1
  • 1
Tallmaris
  • 7,605
  • 3
  • 28
  • 58