Ways to incorporate a search feature for images without relying on a database

Hey there! I've been working on a code that allows users to search for a book by its name and have only the book with that specific name appear on the page. However, I've run into an issue where the search function doesn't seem to be working properly.

Here's the code I have so far:

      var search = $("#search-criteria");
  var items  = $(".image-wrap");

  $("#search").on("click", function(e){

       var v = search.val().toLowerCase();
      if(v == "") {
          items.show();
          return;
      }
       $.each(items, function(){
           var it = $(this);
           var lb = it.find("id").text().toLowerCase();
           console.log( lb + " --- " + v);
           if(lb.indexOf(v) == -1)
                it.hide();
       });
   });
});
  .review-img {
  cursor: pointer;
  height: 160px; // height
  //width: 30%; // width
  }
    <form>
          <div> <input type="text" id="search-criteria" id="searchText"/>
    <input type="button" id="search" value="search" onClick="tes();"/> </div>
         </form>

    <section class='images'>
<img class="review-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi"></img>
<img class="review-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" alt="kiterunner"></img>    
<img class="review-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" alt="starwars"></img>
<img class="review-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" alt="twilight"></img>
</section>

Answer №1

There are a few adjustments that need to be made in the script

<script type="text/javascript">    
    $(document).on("click","#search",function(e){
           var search = $("#search-criteria");
           var items  = $(".review-img");
           var v = search.val().toLowerCase();
           if(v == "") {
              items.show();
              return;
           }
           $.each(items, function(){
               var it = $(this);
               var lb = it.attr("id").toLowerCase();
               console.log( lb + " --- " + v);
               if(lb===v)
                    it.show();
                else
                    it.hide();
           });

      });
    </script>

This solution should work as expected. It's also important to remove onClick from the input button since the search will be based on the button's id.

If you have any more questions about this code, feel free to ask

Answer №2

It is important to carefully examine the following line of code:

var lb = it.find("id").text().toLowerCase();

You should familiarize yourself with the functionality of the find method---calling find("id") does not retrieve the id of each element as you might expect.

Answer №3

To utilize the <datalist> element, assign the .value of child <option> elements to the .image img id. Set the list attribute of the #search-criteria element to the id of the <datalist> element. Hide the .images img elements using .hide(). Upon clicking the #search button, invoke .show() on the .value of the #search-criteria.

It's worth noting that the <img> tag is self-closing.

$(".images img").each(function() {
  $("#images").append(new Option(this.id, this.id));
}).hide();

$("#search").on("click", function(e) {
  e.preventDefault();
  $(".images img").hide()
  .filter("#" + $("#search-criteria").val())
  .show()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form>
  <div> <input type="text" id="search-criteria" id="searchText" list="images" />
    <input type="button" id="search" value="search" />
    <datalist id="images"></datalist>
  </div>
</form>

<section class='images'>
  <img class="review-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi">
  <img class="review-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" alt="kiterunner">
  <img class="review-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" alt="starwars">
  <img class="review-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" alt="twilight">
</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A Javascript callback function does not alter the contents of an array

I have been working on a project to create a task list page, where I retrieve the items from a mongodb database. When I use console.log(item) within the callback function, each item is printed successfully. However, when I use console.log(items) outside o ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Is the HTML5 capture attribute compatible with wkwebview?

Is it supported as stated in the title? For more information, you can check out the MDN documentation (Incomplete) and the Caniuse list of supported browsers. Surprisingly, none of them mention wkwebview. Does this attribute have support in wkwebview? Kno ...

What is the best way to utilize v-select for searching entries while also allowing users to type in text within the input field for the search?

How can I implement a fold-out display for entries in a v-select field while also enabling text search functionality to find specific items? Are there any Vuetify props that address this, or do you have any suggestions on how to approach this? <v-sele ...

What is the process for connecting a Wii Remote with Three.js?

Suppose I wanted to explore Wii Remote to browser interaction by connecting it to my Ubuntu laptop via Wiican and Wmgui using Bluetooth. What would be a simple program to achieve this? I have successfully used an Xbox Gamepad with Chrome, so I know that i ...

What is the method for dividing a string (object) to 'preserve' in a fresh piece?

Upon receiving the following JSON file: var data = [ { "id":"1", "yMonth":"201901", }, { "id":"2", "yMonth":"201902", }, { "id":"3", "yMonth":"201802", }, { "id":"4 ...

Create a new promise within a factory function

I am facing an issue in my factory where I want to return a promise inside a function, but every time I try, my controller throws an error like: Provider 'personFactory' must return a value from $get factory method. This is how my factory looks ...

Node.js Express Issue: Module Not Found

Having trouble launching an express app in docker with node 10.9.0 due to an import problem: root@e85495ae1c9e:/usr/app/backend# node app.js internal/modules/cjs/loader.js:583 throw err; ^ Error: Cannot find module '/usr/app/backend/models/todo&ap ...

Remove character when the button is clicked as long as the input value is not equal to 0

I am currently using the code below to remove a character from an input field: function deleteChar(input) { input.value = input.value.substring(0, input.value.length - 1) } However, if there is only one character in the input field and the function is ...

Issues with the functionality of the bootstrap modal jQuery function in Firefox, causing problems with scrollbars and dynamic modal height adjustments

My newly launched website is built using bootstrap v3 and modals to showcase detailed information about each game server that is queried. Each modal provides insights into the current players on the server, their score, and play time. While implementing ...

enhance the brilliance of elements at different intervals

My latest CSS animation project involves creating a stunning 'shine' effect on elements with a specific class. The shine effect itself is flawless, but having all elements shine simultaneously is making it look somewhat artificial. I've bee ...

Having trouble retrieving JSON data using http.get method, as the status returned is -1

I'm a beginner in AngularJS. I'm attempting to retrieve JSON data in my code using $http.get, but it's throwing an error and the status is showing as -1. What could be causing this issue? RecordApp.factory('recordaccess', [' ...

Displaying images in a horizontal row instead of a vertical column when using ng-repeat

I am currently using ng-repeat to showcase a series of images. While I believe this may be related to a CSS matter, I am uncertain. <div ng-repeat="hex in hexRow track by hex.id"> <img ng-src="{{hex.img}}"/> </div> https://i.sstatic ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Struggling with implementing CSS in React even after elevating specificity levels

I am struggling with a piece of code in my component that goes like this: return ( <div className="Home" id="Home"> <Customnav color="" height="80px" padding="5vh"/> <div className= ...

jQuery does not seem to be able to recognize the plus sign (+)

I am currently developing a calculator program and facing some challenges with the addition function. While the other functions ("/", "-", "*") are working fine, the plus ("+") operation seems to be malfunctioning. Here's the snippet of HTML and JavaS ...

An unexpected confusion regarding the use of jQuery

I'm a beginner with jQuery and I'm struggling to understand this particular line of code: $('<div></div>').prependTo('body').attr('id', 'overlay'); Could someone please provide an explanation ...

Setting a default value in a multiselect dropdown when no options are selectedIf no options are selected in

When using razor syntax, I aim to set the value to 0 if the dropdown is not selected or if the dropdown text is 'select one'. Additionally, I have multiple dropdowns and I am retrieving this value through form collection. @Html.DropDownListFor(m ...

Tips for accessing a variable located in a different directory

I'm facing some confusion regarding creating a global variable that can be accessed in another file. Currently, I have a chat and login folder setup. Within the login folder, there are three possible users to choose from. When a user clicks on one of ...

Tips for selecting the first item when cloning using JQuery

Here is an example of my code: $('.cloneMe').on('click', function(e) { var idToAppend = $(this).data('id'); $(this).data('id', idToAppend + 1); $('div.render-form-editlayout-10').clone("").find ...