The filter search feature fails to return any results when data is inputted into the tables

I have implemented a filter search feature within two tables on my website.

My goal is to retrieve the search results for a specific drink while keeping the table headings fixed in their positions.

For instance, if I type "Corona" into the search box, I expect to see "Corona" displayed along with the heading for Spirits even if there are no matching items under that category.

I seem to be encountering some issues and can't figure out what went wrong.

* {
  box-sizing: border-box;
}

#myInput {
  width: 40%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  border-radius:7px;
  margin-bottom: 12px;
  margin-left:45px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin-left:45px;
  display: block;
}

#myUL li a {
  border: 1px solid #ddd;
  border-radius:7px;
  margin-top: -1px; /* Prevent double borders */
  width:30%;
  padding: 8px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  background-color:#f6f6f6;
  display: block;
}
  
.t1 {
    float:left;
    background:yellow;
    margin-left:10px;
}

.t2 {
    float:left;
    background:cyan;
    margin-left:50px;
}

li {list-style-type: none;}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Enter keyword to search" title="Example: Account NT">

<br>
 
<table class="t1">
<tr>
        <th>SPIRITS</th>
    </tr>
<ul id="myUL">
<tr><li><td>Armagnac</td></li></tr>
    <tr><li><td>Gin</td></li>
    <tr><li><td>Vodka</td></li></tr>

</table>

<table class="t2">
    <tr>
        <th>BEERS</th>
    </tr>
    <tr><td><li>Budweiser</li></td></tr>
    <tr><td><li>Corona</li></td></tr>
    <tr><td><li>Heineken</li></td></tr>
    </ul>
</table>
<script>
  function myFunction() {
      var input, filter, ul, li, a, i,;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");

    for (i = 0; i < li.length; i++) {
          a = li[i].getElementsByTagName("a")[0];
          if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
              li[i].style.display = "";
          } else {
              li[i].style.display = "none";

          }
      }
  }
</script>

Answer №1

Here is a revised version of your code to assist you.

const filterInput = document.getElementById('myInput');
const drinks = document.querySelectorAll('.drink-name');

filterInput.addEventListener('keyup', function(e) {
  const searchQuery = e.target.value.toLowerCase();
  
  drinks.forEach((drink) => {
    if (searchQuery.length > 2) {
      if (drink.textContent.toLowerCase().indexOf(searchQuery) < 0) {
        drink.style.display = 'none';
      } else {
        drink.style.display = 'block';
      }
    } else {
      drinks.forEach((drink) => {
        drink.style.display = 'block';
      });
    }
  });
});
#myInput{
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  border: 1px solid #CCC;
}
.list{
  float: left;
  padding: 10px;
  margin-right: 20px;
  list-style: none;
}
.list li:nth-child(1){
  font-weight: bold;
  margin-bottom: 5px;
}
#list1{
  background: yellow;
}
#list2{
  background: cyan;
}
<input type="text" id="myInput" placeholder="Enter word to search">

<br>
 
<ul id="list1" class="list">
  <li>SPIRITS</li>
  <li class="drink-name">Armagnac</li>
  <li class="drink-name">Gin</li>
  <li class="drink-name">Vodka</li>
</ul>

<ul id="list2" class="list">
  <li>BEERS</li>
  <li class="drink-name">Budweiser</li>
  <li class="drink-name">Corona</li>
  <li class="drink-name">Heineken</li>
</ul>

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

Is there a way to manipulate the appearance of a scroller using JavaScript?

I'm intrigued by how fellow front-end developers are able to customize the scrollbar shape on a webpage to enhance its appearance. Can anyone guide me on using JavaScript to accomplish this? ...

Is there a clash between ng-if and col col-50?

Currently, I am attempting to create a table using Angular code within HTML. The structure of the table is exactly how I want it to be, and here is the code snippet representing it: <div class="row"> <div class="col col-25">Date</div> ...

Having difficulty accurately interpreting the input value

As someone new to JavaScript, I set out to create a basic calculator using JavaScript and HTML. My goal is to have two input fields, named Fld1 and Fld2, that would add up the values entered into them when submitting. However, despite parsing the input val ...

What are the steps to ensure HTML5 video fills the entire height and width of the browser window?

Is there a way to make a video fill the entire width and height of the browser on first page load using bootstrap? I am currently facing some issues with achieving this. The code that I have been using seems to work, but the height ends up being more than ...

Tips for creating a centered Reindeer

My reindeer code seems to be a bit off-center. Even though I followed a tutorial, my reindeer is not aligning properly as shown in the tutorial. Here is all the CSS code for the reindeer: .reindeer { height: 510px; width: 350px; position: ab ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Is it possible to incorporate button classes from the <a> tag into a JQuery fade in/fade out function?

My jQuery image thumb Slider features thumb buttons that link to different div elements. When a user clicks on a thumb button, I want the associated div to smoothly fade in, replacing the previous one. The goal is to have a seamless transition between the ...

What is the best way to retrieve the value of a button using javascript?

After trying to extract the value from a button in JavaScript, here is the code I used: for(i=0; i<cars.length;i++){ var p = `<button id="myBtn" onclick="myFunction()" value="${cars[i]}">${cars[i]}</button>` func ...

Place CSS elements in relation to the underlying element

This is an example of my HTML structure: <nav id="menu"> <ul> <li><a href="">Products</a></li> <li><a href="">Offers</a></li> <li><a href="">References</a>& ...

How to link a sandbox file in HTML with an iPhone

Looking to create an HTML application specifically for the iPad, I am interested in developing a background process using Objective-C that will handle the downloading of images and data. The goal is to be able to access these resources from within an HTML ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Building a Dynamic Checkbox Validation Feature in Angular Using Data retrieved from an API

Currently, I have a function that retrieves and displays a list obtained from an API: displayEventTicketDetails() { this.Service .getEventTicketDetails().subscribe((data: any) => { this.eventTicketDetails = data.map(ticket => ticket. ...

Tips for effectively utilizing an if/else structure to animate fresh content from the right while smoothly removing old content by sliding it to the left

document.getElementById("button1").addEventListener("click", mouseOver1); function mouseOver1(){ document.getElementById("button1").style.color = "red"; } document.getElementById("button2").addEventListener("click", mouseOver); function mous ...

Challenges with resizing floating divs

As a beginner in Web Development, I am tasked with creating a web portfolio for an assignment. In my design layout, I have a navigation bar in a div floated left, and a content div floated right serving as an about me section containing paragraphs and lis ...

Is it possible to create a d3 gauge chart showcasing data with both labels and

We've been on the hunt for a radial chart that resembles the one shown below. What makes this chart stand out is the clear display of percentage values. Despite our search efforts over three days, we have yet to come across anything using the d3.js li ...

Run a PHP script on the current page upon choosing an option from a dropdown list with the help of Ajax or JavaScript

I'm currently working on a MySQL query that needs to be executed when a user selects options from multiple dropdown lists. What I am looking for is the ability to automatically run a query related to the selected dropdown list option using AJAX/JavaS ...

The image fails to display when using THREE.js and Panolens.js

Trying to create a 360-degree environment with informational buttons using THREE.js and Panolens.JS However, I'm unable to resolve why the image is not appearing. Continuously encountering the error: Uncaught ReferenceError: process is not defined. ...

Exploring the Breakpoints of Bootstrap 4.x Grid System in Development

Understanding the grid system in Bootstrap 4.x can be beneficial, especially when trying to determine the specific grid breakpoint that aligns with the current viewport width. ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

What is the best way to display noscript content within my Angular application?

What is the best way to show HTML content for users who do not have JavaScript enabled in my Angular application? Inserting the noscript tag directly into the index.html file does not seem to be effective. <body> <noscript>Test</noscrip ...