Skip to content
Advertisement

JQuery Search function for div containers

I am trying to use JQuery and this script (to filter my mySql output):

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#notes div").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

the mySql entries I want to filter look like this in html:

<div class="card" id="notes">
    <div class="card-header">
        <div class="float-left">
            <h5 class="card-title float-left">Title ABC</h5>
        </div>
    </div>
    <div class="card-body">
        <p class="card-text">Text XYZ</p>
    </div>
    <div class="card-footer">
        <div class="float-left">
            <p class="card-date">Date 2020-03-13</p>
        </div>
    </div>
</div>

so each <div class="card" id="notes"> is one entry.

The problem is (as you can see) I probally use this function wrong because I filter $("#notes div").filter(function() {

so if I search “ABC” the script only display the div container which is containing the “Title ABC”. same goes if I search “XYZ” etc.

So what I want is. Whatever I search for it shouls display the whole div container <div class="card" id="notes"> where the search entry is found in either title, text or date.

would someone be so kind to explain me how I can make it working? I am thankfull for every tipp or even a link to a good tutorial I can work with.

thanks in advance and best greetings.

Advertisement

Answer

#notes is only targetting 1 .card. "#notes div" then filters divs within it. If you want to filter .card‘s by their text content, you should find all .cards by searching on their parent like this:

const value = "xyz";
$(".cards .card").filter(function(i, el) {
  const $card = $(el);
  $card.toggle($card.text().toLowerCase().indexOf(value) > -1)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cards">
  <div class="card" id="notes">
    <div class="card-header">
      <div class="float-left">
        <h5 class="card-title float-left">Title ABC</h5>
      </div>
    </div>
    <div class="card-body">
      <p class="card-text">Text XYZ</p>
    </div>
    <div class="card-footer">
      <div class="float-left">
        <p class="card-date">Date 2020-03-13</p>
      </div>
    </div>
  </div>
  <div class="card" id="songs">
    <div class="card-header">
      <div class="float-left">
        <h5 class="card-title float-left">Title Hmm</h5>
      </div>
    </div>
    <div class="card-body">
      <p class="card-text">Text xYz</p>
    </div>
    <div class="card-footer">
      <div class="float-left">
        <p class="card-date">Date 2020-03-13</p>
      </div>
    </div>
  </div>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement