javascripthtmlfilterfunction

Filter divs based on text input


I'v got 2 layout for my filter div. 1 specific for desktop devices and 1 for mobile. I want it to filter items based on the text input the user gives. This is input div

<div class="search-wrapper">
  <input class="searchInput TextFilter-mobile" type="text" onkeyup="searchFunction()" placeholder="Zoeken..">
</div>

Now i got 2 separate divs that appear on the right device: First the mobile one:

  <div class="card card-filterDiv zuivel special">
    <div class="card-horizontal">
      <div class="image-wrapper">
         <img class="clip-product-img-mobile" src="{% static 'main/images/img3.jpg' %}" alt="Card image cap">
         <button class="btn btn-success">
           <i class="fas fa-cart-plus add-to-cart-icon"></i>
         </button>
      </div>
      <div class="card-body">
       <h2 class="food card-title mr-0" style=">Bokkenpootjes</h2>
      </div>
    </div>
  </div>

And this is the desktop one:

<div class="card card-filterDiv special zuivel">
  <img class="card-img-top clip-product-img-desktop" src="{% static 'main/images/img3.jpg' %}" alt="Card image cap">
    <button class="btn btn-success">
      <i class="fas fa-cart-plus add-to-cart-icon""></i>
    </button>
  <div class="card-body">
     <h2 class="food card-title mr-0">Bokkenpootjes</h2>
  </div>
</div>

I have made a function which handles the logic:

function searchFunction() {
  // necessary variables
  var input, filter, card, h2, a, i, txtValue;
  input = document.querySelector(".searchInput");
  filter = input.value.toUpperCase();
  cardfilter = document.getElementsByClassName('card-filterDiv');


  // Loop through all cards, and hide those who don't match the search query at h2 Tag
  for (i = 0; i < cardfilter.length; i++) {
    a = cardfilter[i].getElementsByTagName("h2")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      cardfilter[i].style.display = "";
    } else {
      cardfilter[i].style.display = "none";
    }
  }
}

It works correctly on the mobile HTML but it is not on the desktop (second 1). I get no errors and everything seems to be OK. What am I missing?


Solution

  • Fixed it. js can't handle two seperate input field on 1 function. Made a textinput for desktop as well as for mobile. My mistake!