jquerysearchfilteralt

Jquery search filter for images based on ALT tag


I'm building a search page for an image gallery based on the alt tag. The gallery will eventually have over 3000 pics. Only images matching text from the search bar are shown. The page is updated as you type, reflecting the current matches. I have a good working model so far, thanks to posts I've found here addressing almost the same task. I need my search filter to be insensitive to case and spaces. My current code works almost as intended, with one small issue. The input from search bar will not show any matches for numeric characters in the alt tag.

$('img').hide();

$("#myinput").keyup(function() {
  var val = $.trim(this.value);
  val = val.split(" ").join("\\ ");
  if (val === "")
    $('img').hide();
  else {
    $('img').hide();
    $("img[alt*=" + val + " i]").show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myinput" name="search" placeholder="search..." style="width:200px; height: 40px; border-radius: 4px; font-size: 18px;"><br>
<div id="images">
  <a href="https://example.com"><img src="https://picsum.photos/id/100/200/300" alt="Beach 194888" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1002/200/300" alt="Earth 2069" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1003/200/300" alt="Bambi" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1015/200/300" alt="River" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1027/200/300" alt="Roksolana Zasiadko" width=130></a>

</div>


Solution

  • This will filter on case insensitive input with or without digits

    const $img = $("#images img");
    $("#myinput").on("input",function() {
      $img.hide();
      const val = this.value.trim().toLowerCase();  
      if (val === "") return; 
      $img.filter(function() { return this.alt.toLowerCase().includes(val)  }).show()
    });
    #images img { display: none }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="myinput" name="search" placeholder="search..." style="width:200px; height: 40px; border-radius: 4px; font-size: 18px;"><br>
    <div id="images">
      <a href="https://example.com"><img src="https://picsum.photos/id/100/200/300" alt="Beach 194888" width=130></a>
      <a href="https://example.com"><img src="https://picsum.photos/id/1002/200/300" alt="Earth 2069" width=130></a>
      <a href="https://example.com"><img src="https://picsum.photos/id/1003/200/300" alt="Bambi" width=130></a>
      <a href="https://example.com"><img src="https://picsum.photos/id/1015/200/300" alt="River" width=130></a>
      <a href="https://example.com"><img src="https://picsum.photos/id/1027/200/300" alt="Roksolana Zasiadko" width=130></a>
    
    </div>