Home > Back-end >  jquery filter based on button text
jquery filter based on button text

Time:10-21

I woul like to ask for some help / advise. I would like to filter all <p> which contain the button text. I'm stucked a little bit. THANK YOU for the support!!

$(document).ready(function() {
  $("button").click(function() {
    var button = $(this).text().toLowerCase();
    $(".color").filter(function() {
            $(".color").toggle(jQuery(".color p").text().toLowerCase().indexOf(button) > -1)
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <button>Show All</button>
  <button>Green</button>
  <button>Red</button>
  <button>Blue</button>
</div>
<div >
  <div >
    <h1>Name</h1>
    <p>Red Green</p>
  </div>
  <div >
    <h1>Name</h1>
    <p>Green</p>
  </div>
  <div >
    <h1>Name</h1>
    <p>Red Blue</p>
  </div>
  <div >
    <h1>Name</h1>
    <p>Green Blue</p>
  </div>
  <div >
    <h1>Name</h1>
    <p>Blue</p>
  </div>
  <div >
    <h1>Name</h1>
    <p>Red </p>
  </div>
  <div >
    <h1>Name</h1>
    <p> Green</p>
  </div>
  
  
</div>

CodePudding user response:

:contains(_your_text_) would help you if you want to get the inner text of the element. Since you are filtering the text but there are case sensitive from the text, so from this Answer we customize and replace the filtering function and it filters without the case sensitive.

Check this out


$(document).ready(function() {
  $("button").click(function() {
    var button = $(this).text().toLowerCase();
    
    $('.color p:contains('  button  ')').toggle()
    // do what u want to the element
        
  }); // end of click button
});

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

  • Related