Wednesday, 18 September 2013

Creating a custom selector in jQuery for case insensitive search

Jquery Custom Selector

jQuery supports a wide range of selectors out of which :contains() is a selector that returns the containers / elements that contains the given content.

This can be used to search / filter the content using jQuery.

But the :contains() selector is a case sensitive.

Let me demonstrate you the working of the :contains() selector

Case sensitive search using contains :
Apple
Mango
Banana
Grapes
Watermelon

Code used in the demo

     
$("#txtsearch").keyup(function(){
 if($.trim($(this).val()) != "")
 {
  $("div.legends").removeClass("tempselector");
  
  $("div.legends").parent().children(":contains('"+$.trim($(this).val())+"')").each(function(){
   $(this).addClass("tempselector");
  });
  
  $("div.legends.tempselector").show();
  $("div.legends:not('.tempselector')").hide();
  
  $("div.legends").removeClass("tempselector");
 }
 else
 {
  $("div.legends").show();
 }
});
     
    

Now if we want a selector which filters the contents but is case insensitive we will need a custom selector say :icontains() that searches the contents of the containter / element but the search is case insensitive.

To create the selector, I am demonstrating two options


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

OR


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

Either of them will do the same work, the first one is created using $.extend and the other is a simple way to create a selector

Below stated is the demo for case insensitive searching

Case sensitive search using custom selector icontains:
Apple
Mango
Banana
Grapes
Watermelon

Code used in the demo

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

$("#itxtsearch").keyup(function(){
 if($.trim($(this).val()) != "")
 {
  $("div.ilegends").removeClass("itempselector");
  
  $("div.ilegends").parent().children(":icontains('"+$.trim($(this).val())+"')").each(function(){
   $(this).addClass("itempselector");
  });
  
  $("div.ilegends.itempselector").show();
  $("div.ilegends:not('.itempselector')").hide();
  
  $("div.ilegends").removeClass("itempselector");
 }
 else
 {
  $("div.ilegends").show();
 }
});
     
    

You can download the demo file here

No comments:

Post a Comment