12

I'm trying to compare a string given in an input to a div's content using jQuery contain.

Problem is, I want to be able to check if the string is contained regardless of upper/lower case.

This is my function:

$(document).ready(function() {
    drawDimensions('dContent');
    $('#dSuggest').keyup(function() {
        var dInput = this.value;
        $(".dDimension:contains('" + dInput + "')").css("display","block");
    });
});

So if one of the .dDimension divs contains 'Date' and a user presses the 'd' key, I want to show that item.

is it possible?

Or Weinberger
  • 7,332
  • 23
  • 71
  • 116
  • 1
    possible duplicate of [Is there a case insensitive jQuery :contains selector?](http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector) – Shadow The GPT Wizard Jan 09 '12 at 22:03

4 Answers4

28

You can use .filter [docs]:

var dInput = this.value.toLowerCase();

$(".dDimension").filter(function() {
    return $(this).text().toLowerCase().indexOf(dInput) > -1;
}).css("display","block");
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can write your own selector by extending jQuery. Try this

$.extend($.expr[':'], {
  'containsi': function(elem, i, match, array)
  {
    return (elem.textContent || elem.innerText || '').toLowerCase()
    .indexOf((match[3] || "").toLowerCase()) >= 0;
  }
});

Useage $(".dDimension:containsi('" + dInput + "')").css("display","block");

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1

Have a look at this example, he extend the jQuery selectors with a case-insensitive contains selector that he calls containsi, like this:

$.extend($.expr[':'], {
   'containsi': function (elem, i, match, array) {
       return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || '').toLowerCase()) >= 0;
   }
});
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
0

The last comments in the jQuery documentation for contains provides an 'icontains' implementation that may suit you.

$.expr[':'].icontains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};

// Example usage.
$("div:icontains('John')").css("text-decoration", "underline"); 
mqsoh
  • 3,180
  • 2
  • 24
  • 26