How to use jQuery selector to filter jQuery isotope items case-insensitive (search)

StackOverflow https://stackoverflow.com/questions/9492366

  •  14-11-2019
  •  | 
  •  

Pergunta

I'm playing around with jQuery Isotope and want to implement an element search. When the user types into a text box, I change the filter option like this:

var newFilter = '[data-myAttr*="' + $('#mySearchBox').val() + '"]';
$('#myIsotopeContainer').isotope({filter: newFilter});

I'm using jQuery's attribute contains selector. But it's case-sensitive, and I want to be case-insensitive. How can I accomplish this?

I've looked at other questions and Google results that suggest using .filter(fn), but I don't have that much control with isotope. I just give it a selector.

Foi útil?

Solução

use lower case as protocol for all attributes and then change user input to lowercase

Outras dicas

From looking at Isotope's source, you should be able to pass a function, like this:

$('#myIsotopeContainer').isotope({ filter: function() {
        // case-insensitive pattern match:
        var pattern=new RegExp($('#mySearchBox').val(),'i');

        // test against 'data-myAttr':
        return pattern.test(this.attr('data-myAttr'));
    }
});

Isotope simply makes a .filter() call to do it's own filtering. Give it a try and see what happens.

I want to give an answer that is related to this question for people like me who are doing this a little bit differently. I wanted to search any text in the whole element (or any children of the element), and not just an attribute. If you are using the :contains selector and want it to be case-insensitive, you should extend JQuery as outlined in this bug report. I'm posting the code below for convenience:

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

Now you can use the JQuery like you would have using :contains('SomeString') but now use your new extended :containsi('SomeString')

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top