Show divs based on text search

后端 未结 4 1607
情深已故
情深已故 2020-12-28 15:49

I have a text input search that is supposed to filter divs based on the title of the div. Here is the code that is not working:

$(\'.contact-name\').each(fun         


        
相关标签:
4条回答
  • 2020-12-28 16:00

    The find method takes a JQuery selector as parameter. I doubt your search_criteria text input will contain that. Assuming it will contain some substring of the DIV's title, then try this:

    var txt = $('#search-criteria').val();    
    $('.contact-name').each(function(i, e){
      if($(e).attr("title").indexOf(txt)>=0) $(e).show();
    });
    
    0 讨论(0)
  • 2020-12-28 16:12

    The following should be case-insensitive, and match only on text in first a href in the div:

    var pattern = "/" + $('#search-criteria').val() + "/i";
    $('.contact-name').filter(function() {
        return $(this 'a:first-child').html().match(pattern).length > 0;
    }).show();
    

    filter gives you a list of elements that return true from that function in it to apply show() to.
    The return in the filter function can be read as: "for the first anchor element in this element, take the contents, match it against the pattern, and if the resulting array contains 1 or more results, return true".

    The "i" on the end of the pattern is what gets you case-insensitive matching.

    0 讨论(0)
  • 2020-12-28 16:16

    Luckily jQuery has a Contains selector:

    $('.contact-name').each(function(){
      var txt = $('#search-criteria').val();
      $(this).find('div:contains("'+txt+'")').show()      
    });
    
    0 讨论(0)
  • 2020-12-28 16:17

    try this

    var txt = $('#search-criteria').val();
    $('.contact-name:contains("'+txt+'")').show();
    

    documentation for :contains() Selector

    fiddle example : http://jsfiddle.net/WBvTj/2/

    UPDATE CASE INSENSITIVE:

    var txt = $('#search-criteria').val();
    $('.contact-name').each(function(){
       if($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1){
           $(this).show();
       }
    });
    

    fiddle Example : http://jsfiddle.net/WBvTj/4/

    0 讨论(0)
提交回复
热议问题