ways to conceal list elements using an HTML search box

Is there a way to hide list items from the filter in an HTML search box?

For example, I only want the items to show when I click on the search box and then display the item list.

Otherwise, I would like the list items to be hidden under normal conditions.

  • Adele
  • Agnes
  • Billy
  • Bob
  • Calvin
  • Christina
  • Cindy
  • kandy
  • lakum
  • kool
  • moon
  • noon

If anyone can provide a correction for this, please do so.

<!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;
        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>

    </body>
    </html>

If anyone has suggestions for improvements, please feel free to share them.

Answer №1

To achieve this functionality, the idea is to initially hide the UL element when the DOM is fully loaded and then show the list once the input field receives focus. You can implement this feature using jQuery by following the code snippet below.

 $(function(){
  $('#myUL').hide();
  $('#myInput').on('focus',function(){
    $('#myUL').show();
  });
})

Answer №2

If you are looking at your "myUL" list: -Assign a specific class to each item in the list

<li class='people'>Adele</li>)

Next, include a CSS feature to initially conceal the entire list

  • .people { display: none;}

When it comes to javascript: Revise this portion:

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

To be more precise (reverse the if-else and check if filter is empty):

if (!(a.innerHTML.toUpperCase().indexOf(filter) > -1)) && filter == "")
    {
    li[i].style.display = "none";
    } else {
        li[i].style.display = "block";
    }
}

Answer №3

Hello everyone! After trying numerous solutions without success, I finally stumbled upon the one that works like a charm.

Here is the solution:

  1. Add a class="search-bar-items" (in HTML) to all of the lists

  2. In your CSS file, include the following code:

    .search-bar-items{ display:none; }

Example of list with the class name search-bar-items

CSS property example

Answer №4

Everything should be set for you to proceed

<!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>Digital Address Book</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Enter a name to search.." title="Find a contact">
<ul id="myUL">
  <li><a href="#">Alice</a></li>
  <li><a href="#">Brian</a></li>
  <li><a href="#">Charlie</a></li>
  <li><a href="#">David</a></li>
  <li><a href="#">Emily</a></li>
  <li><a href="#">Frank</a></li>
  <li><a href="#">Grace</a></li>
</ul>

<script>
var UL = document.getElementById("myUL");
// hide the list by default
UL.style.display = "none";

var searchBox = document.getElementById("myInput");

// show the list when the input receives focus
searchBox.addEventListener("focus",  function(){
    // UL.style.display = "block";
});

// hide the list when the input receives focus
searchBox.addEventListener("blur", function(){
    UL.style.display = "none";
});


function myFunction() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    ul = document.getElementById("myUL");
    filter = input.value.toUpperCase();
    // if the input is empty, hide the list
    if(filter.trim().length < 1) {
        ul.style.display = "none";
        return false;
    } else {
        ul.style.display = "block";
    }
    
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        
        // This is when you want to find words that contain the search string
     if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { 
        li[i].style.display = "";
     } else {
        li[i].style.display = "none";
    } 
    
    // This is when you want to find words that start with the search string
    /*if (a.innerHTML.toUpperCase().startsWith(filter)) {
        li[i].style.display = "";
    } else {
        li[i].style.display = "none";
    }*/
    }
}
</script>

</body>
</html>

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

Ways to simultaneously apply fade in and fade out effects using CSS

body { background-image: url("background.jpg"); background-attachment: fixed; font-family: 'Roboto', sans-serif; color: #333333; } #container { height: 1000px; } /* HEADER WITH NAVIGATION BAR AND LOGIN OPTION */ #head { position: abso ...

Slice the towering text in half lengthwise

Ensure that the last line of visible text fits within a 20px padding, or else it should be completely cut off. The challenge lies in the varying text lengths of h3 each time. It's difficult to predict how much needs to be trimmed. Currently, the tex ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

The angular2-webpack-starter kicks off with a simple static page

When starting my project using angular2-webpack-starter, the initial loading of index.html allows us to create our own components. However, in my case, I am looking to first direct users to a static page without any Angular code before clicking a button th ...

Issue with sizing and panning when using a combination of Three.js and CSS3Renderer

This issue is specific to Chrome. Here's what I have experimented with: I am utilizing the webGL renderer to position a plane geometry in a 3D environment using threejs. This particular code is running within a class, with the scene as one of its me ...

Access an HTML page programmatically using JavaScript

Make sure to have a confirmation window pop up before submitting the form, and after confirming submission (by clicking OK), redirect to a confirmation page. Here's an example code snippet: <button type="submit" value="Save" id="Save" onclick="cl ...

Horizontalize your lists

Is there a way to make the li elements horizontal in this pagination setup? I've attempted display: inline and display: float, but neither seem to be working for me. <ul class="pagination" style="display:inline; text-align: center; margin:0;">& ...

Looking for an Effortless Loading jQuery Image Slider or: Unleashing the Power of cross-slide

I am in need of assistance with implementing lazy loading for images in a jQuery slideshow that pulls from Flickr. Although everything is running smoothly, I would like to optimize the image loading process by only loading them on demand. Currently, I am ...

Exploring Laravel: A Guide to Sending JSON Data from Controller to View Using Ajax(GET)

I'm encountering a challenge at the moment. I've been attempting to pass a specific date to the controller (in order to create a where clause and send it back to the view), but it seems unnecessary to use a controller for this purpose since a whe ...

Enhancing Bootstrap project with personalized CSS styling

Utilizing SCSS to create my CSS has been the approach I've taken. The content of my main.scss file remains consistent even after it is compiled into css. .my-custom-row { background-color: bisque; } Contained within my index.html file is everythi ...

Tips for adjusting the time format within Ionic 3 using TypeScript

I currently have a time displayed as 15:12:00 (HH:MM:SS) format. I am looking to convert this into the (3.12 PM) format. <p class="headings" display-format="HH:mm" > <b>Time :</b> {{this.starttime}} </p> In my TypeScript code t ...

I am facing an issue where my simple three.js code is not displaying properly

I'm relatively new to three.js and HTML, but I have experience creating other JS files that import into HTML pages without any issues. However, I am confused as to why my basic box code is not showing up on the page when I import the JS file in the sa ...

Tips for centering fontawesome icons in your design

https://i.sstatic.net/Atian.pngI'm facing an issue with aligning 3 icons. My goal is to align them, but every time I attempt something, the first icon ends up in the middle of the page instead of the second icon where I want it to be. .item-icon { ...

Using CSS to create hover effects for specific classes of elements

Is there a way to make the button change color on hover when hovering over anywhere in the navigation bar (.topNav) instead of just when hovering over the individual button elements (.top, .middle, .bottom classes)? I tried using span to achieve this, but ...

Utilizing jQuery Mobile and PhoneGap to incorporate HTML files into data-role=page: A step-by-step guide

I am looking to load HTML files into a data-role=page using jQuery Mobile and PhoneGap. My project consists of several small HTML files with separate pages. In my implementation, I have: index.html: <!DOCTYPE html> <html> <head> ...

Stay updated with instant notifications on incoming messages!

Consider this scenario: we are implementing a message notification system for our website users. What I aim to achieve is that when a new message is sent to a member while they are actively using their inbox, they should receive a real-time notification ab ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

Deciding Between Javascript DOM and Canvas for Mobile Game Development

My idea for a mobile game involves using the Phonegap framework to create a game where players can control a ball's movement by utilizing their phone's accelerometer. I also envision incorporating other elements like enemies and walls into the ga ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...

Maintaining DOM modifications once a link has been clicked and the Back button is pressed

Is there a way in JavaScript to prevent appended items from disappearing when the user clicks another link and then presses the Back button after using jQuery's appendTo() method to add items to an unordered list? ...