Conceal the list items during search queries

I need help filtering a list of items based on user input. Currently, all the items are visible, but I want them to only show up when a user types a name.

I attempted changing the li style to block, but it didn't work as expected.

li[i].style.display = "none";

I am a beginner in JS and currently taking some online courses.

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    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];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
<h2>Car Directory</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Cars" title="Type in a name">

<ul id="myUL">
  <li><a href="#">Volvo</a></li>
  <li><a href="#">BMW</a></li>
  <li><a href="#">Mazda</a></li>
  <li><a href="#">Toyota</a></li>
  <li><a href="#">Yamaha</a></li>
  <li><a href="#">Honda</a></li>
  <li><a href="#">Dodge</a></li>
</ul>

If you can, please check out my pen here: https://codepen.io/emmabbb/pen/wvrpqbp

Answer №1

Ensure the search box is not empty by including filter in the if statement:

if (filter && txtValue.toUpperCase().indexOf(filter) > -1)

and remember to call your function after defining it: myFunction()

**Additionally, for your specific scenario, consider using the input event instead of keyup

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    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];
        txtValue = a.textContent || a.innerText;
        if (filter && txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

myFunction()
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
<h2>Vehicle Listings</h2>

<input type="text" id="myInput" oninput="myFunction()" placeholder="Search for Vehicles" title="Type in a name">

<ul id="myUL">
  <li><a href="#">Audi</a></li>
  <li><a href="#">Mercedes-Benz</a></li>
  <li><a href="#">Ford</a></li>
  <li><a href="#">Lamborghini</a></li>
  <li><a href="#">Porsche</a></li>
  <li><a href="#">Chevrolet</a></li>
  <li><a href="#">Tesla</a></li>
</ul>

Answer №2

If you want to create a searchable car directory using HTML only, you can achieve this without the need for JavaScript.

<h2>Car Directory</h2>
<input list="cars" placeholder="Search for Cars">

<datalist id="cars">
    <option value="Volvo">
    <option value="BMW">
    <option value="Mazda">
    <option value="Toyota">
    <option value="Yamaha">
    <option value="Honda">
    <option value="Dodge">
</datalist>

Answer №3

To start, you can hide the list. Once some input is provided, you can remove the 'hide' class.

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");    
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");    
    li = ul.getElementsByTagName("li");
  
    if (input.value.length > 0)  {
      ul.classList.remove('hide');
    } else {
      ul.classList.add('hide');
    }
  
   
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0; 
}

.hide {
  display: none;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
<h2>Car Directory</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for Cars" title="Type in a name">

<ul id="myUL" class="hide">
  <li><a href="#">Volvo</a></li>
  <li><a href="#">BMW</a></li>
  <li><a href="#">Mazda</a></li>
  <li><a href="#">Toyota</a></li>
  <li><a href="#">Yamaha</a></li>
  <li><a href="#">Honda</a></li>
  <li><a href="#">Dodge</a></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

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Error: When executing the npm run build command, I encountered a TypeError stating that Ajv is not a

I keep encountering an issue whenever I try to execute npm run build error: /node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/validate.js:66 const ajv = new Ajv({ ^ TypeError: Ajv is not a constructor at Object.<anon ...

Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created: function addmovie_post() { { $genre = $this->post('genre'); $cast = $this->post('cast'); $director ...

Apps hosted on Heroku are restricted from accessing CORS, even within the platform's domain

I've been struggling with this problem for a while now. My Nuxt app and service are both hosted on Heroku. After ditching cors(), I added the following code: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*&ap ...

Using JavaScript to extract data from a JSON-formatted URL

I am currently facing a challenge with parsing JSON data from a specific URL. Despite my efforts, I am unable to retrieve any information related to the "ask" and "bid" values from this JSON feed. The URL in question is . The structure of the JSON data is ...

issue with the submit button due to non-functional base64 encoded image

After successfully converting multiple file images to base64 format, I encountered an issue when trying to submit the values. When a user selects multiple images and clicks the submit button, the converted base64 values are returned as undefined. How can t ...

Concerns with the window's onload function

window.onload = prepareButton; function prepareButton() { document.getElementById('slist').onclick = function() { window.location = "students"; } } Whenever I click on a slist element, which is actually a <p> tag formatt ...

I'm new to this, but can someone explain why I'm being redirected to the register_db.php page when I click on the register button?

Why when I click the register button, it redirects me to the register_db.php page instead of sending the data to the database and keeping me on the same register.php page? I want the data to be sent to the database without changing the webpage. register.p ...

Steps to activate a modal window using a double click occurrence within a reactable table

My goal is to initiate a modal window by double-clicking on a cell within a reactable table. Additionally, I need the row index to display an image specific to the clicked row in the modal. The code below successfully triggers a window.alert when a double ...

setting a variable equal to an array element

While I was working on a problem, I encountered a situation that I was able to resolve, but I must admit, I don't fully comprehend how it works. var array = [3, 6, 2, 56, 32, 5, 89, 32]; var largest = 0; //Snippet of my code for (var i = 0; i < ar ...

Is there a way to ensure that the function within the 'for loop' is executed prior to sending the response in NodeJS?

Utilizing bluebird for this task, my main goal is to ensure that the function `get_like_status(email, results[i].id)` located at the end of the for loop runs before sending out the headers. Currently, I am encountering an issue where the array list retur ...

Animating Vue lists using Greensock JS hooks allows for seamless transitions by ensuring that the leave animation completes before triggering the enter

How can Vue be configured to ensure that elements leave a list before new ones enter? Currently, the animations for entering and leaving elements in the list occur simultaneously: var SPEED = 3; var app = new Vue({ el: '.container', data: ...

What is the most efficient way to retrieve a substantial volume of data from Mongodb quickly, especially when the query results require processing before transmitting to the client?

My project involves a large Mongodb database paired with a React front-end and Node back-end, housing around 100000 documents. Indexing has been completed and Redis is already in use. The search feature implemented allows users to find relevant documents b ...

Generate a pre-set Promise<T>[] for delivering the component in the absence of a backend at the moment

I need to implement a function that will eventually make a backend call to fetch data. However, at this moment, I just want to return dummy data to the component. How can I create a hardcoded array of Promises with type IMySetting? export function getMyS ...

Font-awesome integration in Vue.js causing extremely slow hot reloading

Recently, I decided to embark on a fun project using Vue.js because working with this framework seemed enjoyable. To enhance my project, I chose to incorporate the https://github.com/FortAwesome/vue-fontawesome component. However, upon using it in one of m ...

Troubleshooting ASP.NET Content Page Error: jQuery Object Expected

Currently working on designing a personal ASP.NET Web page, I have encountered an issue with making a sticky div using jQuery. Despite all my other jQuery functions functioning properly, the sticky div seems to be causing trouble. stickydiv.js $(document ...

Converting Java 8 LocalDate to a JavaScript Date object

Can you help me with converting a Java LocalDate to a JavaScript Date? Here is the data I have: { "date": { "year": 2016, "month": "NOVEMBER", "dayOfMonth": 15, "monthValue": 11, "dayOfWeek": "TUESDAY", ...

I am facing an issue with the Tailwind Flowbite Datepicker dropdown UI when running "npm run prod" for minification. The class is not being added during minification on the npm

I have successfully integrated a Laravel project with Tailwind CSS. I have also implemented the Flowbite Datepicker using a CDN to include the necessary JavaScript. Initially, everything was working fine and the date-picker was displaying correctly. Howev ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

The drop-down menu continually moves in an erratic manner

These are the functions I have created: function showDropdown() { $(".dropdownitem").show('slow'); } function hideDropdown() { $(".dropdownitem").hide('slow'); } Below is the code for my drop-down menu: <div id="dropdown" ...