jquery filtering case insensitive

2019-08-29 06:39发布

问题:

I found this filtering script:

jsfiddle.net/Zhd2X/574/

Try to press f and F in first table - column boolean. In original version example was working only with f but I added .toLowerCase() in line no. 17. But when you press g or G in second table - column speciality, filtering not working by my first update. I must to change line no. 18, but i dont have any idea...

回答1:

You need to make the text of the <td>s lowercase before filtering. Currently you're only making the value of the filter input lowercase.

var criteria = this.value.toLowerCase();

table.find(el).filter(function(_, td) {
    return $(td).text().toLowerCase().indexOf(criteria) == -1;
}).parent().hide();

Here's an updated fiddle



回答2:

You should create a case insensitive variant of the :contains JQuery selector, by adding the code below to your script. I named it casecontains.

jQuery.expr[':'].casecontains = function(a, i, m) { 
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
};

After that, you can replace your line 17 with the following:

var criteria = ":casecontains('"+$(this).val()+"')";

Note that I just replaced :contains with :casecontains. Also, the conversion to lowercase is no longer needed.

Your updated fiddle.