0

I am trying to implement a search box functionality to a page of images using jQuery. I don't want to use a plugin.

The code I have seems to check to see if search == data attribute instead of looking to see if the data attribute includes search

The search bar is

let images = document.getElementsByClassName('photo-link');

$('#searchbar').on('keyup', function() {
  let search = $('#searchbar').val().toLowerCase();

  $(images).each(function() {
    if (search == $(images).attr('data-alt')) {
      $(this).show();
    } else {
      $(this).fadeOut();

    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section>
  <input id="searchbar" type="search" placeholder="Search" name="search">
</section>


<a class="photo-link" href="photos/01.jpg" data-alt="Hay Bales" data-fancybox="gallery" data-caption="I love hay bales. Took this snap on a drive through the countryside past some straw fields.">
  <img class="photo" src="photos/thumbnails/01.jpg" alt="Hay Bales"></a>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Are you saying you want it to find results that contain the search term instead of results that are equal to the search term? If so, then `==` is not the right way to go... perhaps [string includes](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript)? – devlin carnate Jun 19 '20 at 18:36

1 Answers1

1
  • You are testing all images against search
  • You only lowercase the search
  • If you want to search all images where the data-alt has a partial match, you need to do $(this).attr('data-alt').toLowerCase().includes(search)

This will only show images where the complete search string matches the complete data-alt:

$('#searchbar').on('input', function() {
  const search = $('#searchbar').val().toLowerCase();
  $('.photo-link').each(function() {
    $(this).toggle(search == $(this).attr('data-alt').toLowerCase());
  });
});

You could also play with having the data-alt in one case and do

$('.photo-link[data-alt='+search+']').each(function() { ... })
mplungjan
  • 169,008
  • 28
  • 173
  • 236