Concealing search components using JavaScript

I'm looking to hide elements that appear below the search field in the example code below. The code is sourced from W3: https://www.w3schools.com/howto/howto_js_filter_lists.asp. I only want the search elements to display when a user starts typing in the search field. I am a beginner and seeking a simple solution. Thank you!

    
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  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;
}
</style>
</head>
<body>

<h2>My Phonebook</h2>

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

<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

<script>
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";
        }
    }
}
</script>

</body>
</html>

Answer №1

Answer №2

While these solutions may not be the most elegant, they can still provide valuable insights into how the scripts function. One approach is to initially hide each 'li' element by adding the style attribute with a value of "display:none":

<ul id="myUL">
  <li style="display:none"><a href="#">David</a></li>
  <li style="display:none"><a href="#">Diana</a></li>

  <li style="display:none"><a href="#">Ethan</a></li>
  <li style="display:none"><a href="#">Emma</a></li>

  <li style="display:none"><a href="#">Frank</a></li>
  <li style="display:none"><a href="#">Fiona</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

CodeIgniter functionality for generating auto-incrementing IDs that are accessible in both the view and within JavaScript's Window.Print() method

While working on creating an invoice, I encountered a few issues. First, I want the Invoice No: to be displayed in my view (receipt.php) as 0001 and use it as the primary key in my tbl_payment table. However, I'm unsure how to have an auto-incremented ...

Mistake in maintaining hydration with styled-components and React Context

I encountered an issue where I have two theme variants in my app - dark and light. You can view the sandbox example here ThemeContext.ts export const ThemeContext = createContext<{ theme: AppThemeInterface, setTheme: Dispatch<SetStateAction< ...

Placing the ul tag within a div at the top of the div for proper alignment

I am facing an issue with my code where I cannot get the UL element to appear at the top of the div as it is a child element. <!doctype html> <html> <head> <title>xxx</title> </head> <body> <div id="page" style ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

How to Style Background with CSS on the Server-Side? (Including Links and Hover Effects)

I'm facing a dilemma in choosing between an ASP.NET control and an HTML element for creating a button with a CSS-defined background that changes on hover... 1. Initially, it seems the ASP.NET ImageButton control is not suitable for this purpose becau ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Reinvent the AJAX functionality

Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...

Updating parent data in Vue.js does not automatically trigger an update in the child component

I have the following: Vue.component('times-updated', { template: '<span>Times Updated: {{ timesUpdated }}</span>', data: function() { return { timesUpdated: this.$parent.myData.timesUpdated ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

What could be causing jQuery document ready to restrict access to global variables?

Currently, I am working on a project that involves three separate JavaScript files (example1.js, example2.js, and example3.js) being scripted into a single HTML file (index.html). These JS files are responsible for making an API call and manipulating the r ...

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

Error encountered in Three.js when using multiple canvases and loading JSON geometry

I have been working on creating multiple views and came across an example code here which worked flawlessly when I tried it. However, when I replaced the geometries with ones I created in Blender, I encountered an error: Cannot read property 'length ...

The HTML code starts with a fluid middle column in a 3-column layout, while the other two columns have fixed widths

I am interested in creating a traditional 3-column layout similar to this: | | | | |L | M |R | | | | | I have been tasked with using the following html structure: as depicted, the Main div is the initial node of #container <body> ...

Create a mobile-friendly version of the website that retains all the functionality and features of the desktop

Currently, I am in the process of optimizing my website for mobile devices. However, creating a separate subdomain and folder for a new mobile version is proving to be a challenge since it was not originally requested. How can I ensure that the website ap ...

Getting the image name and extension in an Angular application

Within this block of code, I am working with an image named xyz.abc.jpg. I am able to extract the image extension successfully, but now I need to figure out a way to extract the image name itself without the extension included. Is there a way to achieve ...

PHP loaded HTML does not allow JavaScript to execute

My system includes an announcements feature where all announcements are retrieved from a database and displayed on the screen using Ajax and PHP. Below is the code snippet used to load each announcement onto the page: echo '<div id="announcements ...

Adjusting values in Vue.js with a slider bar

Just starting out with vue.js and wanted to create a slide-bar with min and max values. I came across vue range slider, installed it, and successfully implemented it. The issue I'm facing is changing the value on the slider. The values from my API r ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...

Ajax is capable of sending images as part of the data payload

I am attempting to send data via Ajax, and this data may include an image. Unfortunately, I do not have any forms, so I am unable to submit in the traditional way. Here is my HTML code: <input type="file" accept="image/png,image/jpg,image/jpeg,image/ ...