Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure:

<ul id="fruits">
 <li><a href="#">Mango</a></li>
 <li><a href="#">Apple</a></li>
 <li><a href="#">Grape</a></li>
 <li><a href="#">Cherry</a></li>
</ul>

To hide these items, I have applied the style display: none;. However, users can still search for these hidden fruits using the following input field:

<input type="text" id="searchInput" onkeyup="fruitSearch()" placeholder="Search fruits">

The JavaScript function fruitSearch() allows users to search for fruit names and provides suggestions similar to Google's search feature:

function fruitSearch() {
    // Declare variables
    var input, filter, ul, li, a, i;
    input = document.getElementById('searchInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("fruits");
    li = ul.getElementsByTagName('li');

    // Loop through all list items, and show those that match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "block";
        } else {
            li[i].style.display = "none";
        }
    }
}

Everything works perfectly until the user clears the input field. In this case, all the fruit list items <li> become visible instead of staying hidden.

I am looking for a solution to reset and hide all the list items when the user clears the input field. Any suggestions or ideas?

https://jsfiddle.net/kingBethal/cjbwomof/

Answer №1

First, you should modify your HTML structure by adding the <a> element inside each <li> tag. This is necessary because in your JavaScript code, you are retrieving content from the <a> element.

<ul id="fruits">
 <li><a href="#">Mango</a></li>
 <li><a href="#">Apple</a></li>
 <li><a href="#">Grape</a></li>
 <li><a href="#">Cherry</a></li>
</ul>

Next, you can implement a condition to check if the length of the input is greater than one.

function fruitSearch() {
    // Declare variables
    var input, filter, ul, li, a, i;
    input = document.getElementById('searchInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("fruits");
    li = ul.getElementsByTagName('li');

    if(input.value.length == 0){
        ul.style.display = "none";
        return;
    }else{
        ul.style.display = "block";
    }
    // Loop through all list items and hide those that do not match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "block";
        } else {
            li[i].style.display = "none";
        }
    }
}

Feel free to check out this functional JSFiddle for reference.

Answer №2

Before proceeding further, make sure to include an if statement at the beginning of your function to check whether the value is empty. Based on this condition, you can determine whether or not you should proceed with the remaining code.

var inputValue, filterParam, ulElement, liElements, anchorElement, index;
inputValue = document.getElementById('searchInput');
if (inputValue.value == ''){
  document.getElementById("fruits").style.display = 'none';
} 
else {
  // continue executing the rest of the function
}

Answer №3

Did you know? It is recommended to utilize event listeners instead of using inline events.

    if (document.GetElementById('searchInput').value == '')
    {
        for (i = 0; i < li.length; i++)
        {
            li[i].style.display = none;
        }
    } else {
        // REST OF CODE
    }

Since your function is called during each KeyUp event, simply including the if statement within the function will suffice.

Answer №4

You can employ the power of JQuery's keyup event to achieve a real-time search that takes case sensitivity into consideration. By using the show and hide functions, you can display only the relevant results. Feel free to check out the updated code below:

$("#searchInput").on('keyup', function() {
  var searchedValue = $(this).val();
  performSearchAndFilter(searchedValue)
});

function performSearchAndFilter(searchTerm) {
  if (searchTerm == '') {
    $("#fruits li").hide()
  } else {
    $("#fruits li").each(function() {
      var innerText = $(this).text();
      innerText = innerText.toUpperCase();
      searchTerm = searchTerm.toUpperCase();
      if (innerText.indexOf(searchTerm) >= 0) {
        $(this).show();
      }
    });
  }
}

$(document).ready(function() {
  $("#fruits li").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchInput" placeholder="Search fruits">

<ul id="fruits">
  <li>Mango</li>
  <li>Apple</li>
  <li>Grape</li>
  <li>Cherry</li>
</ul>

Answer №5

It seems that you have obtained this code from a popular coding resource, suggesting that you may have performed a simple copy and paste. To improve upon this, it would be advisable to make further modifications. The original version found on the respective website displays both the items at the beginning and end. Therefore, we can propose a more effective solution by incorporating an if...else statement:

    if(input.value.length === false) {
        ul.style.display = "none"
    } else {
        ul.style.display = "block"
    }

Alternatively, you could consider employing a switch statement.

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

Putting an <input/> element inside a Material UI's <TextField/> component in ReactJS - a beginner's guide

I am attempting to style <TextField/> (http://www.material-ui.com/#/components/text-field) to resemble an <input/>. Here is what I have tried: <TextField hintText='Enter username' > <input className="form-control ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...

The issue of try-catch not functioning properly within a recursive function

Goal My objective is to capture the "Failed to load resource" error and display it in an alert window. Problem I am attempting to handle a video that does not exist. The try catch block is not catching the exception. Scenario I am working on playing vide ...

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

What is causing the delay in retrieving elements using getX() method in Selenium?

Recently, I've been experimenting with web scraping using Selenium. However, I've noticed that there is a delay when calling getText(), getAttribute(), or getTagName() on the WebElements stored in an ArrayList from the website. The website I&apo ...

Node.js publication date displaying incorrectly

When I post a date to elasticsearch, I typically use Date.now() var unixtime = Date.now(); The output usually looks something like this: 1373508091156 To convert it, I then use the following code: var date = new Date(unixtime*1000); After conversion, ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

Spinner displayed upon task completion

Currently, I am developing a project using Spring Boot. I would like to display a spinner on my page to indicate that a task involving heavy calculations is in progress. Even though the page may take up to 5 minutes to load, my spinner only appears for t ...

Employing global variables in JavaScript files with Vue3

In my Vue3 project, I have defined global variables like this: app.config.globalproperties.$locale = locale A composable function has been created to dynamically retrieve these global variables: import { getCurrentInstance ) from 'vue' export f ...

jsTree open_all not triggering consistently

Upon receiving x number of projects and their corresponding directory structure from the server in a single AJAX call, the connection is disconnected from the server. Subsequently, all operations must be carried out from the browser. After loading the pro ...

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...

Incorporate jQuery into Laravel 5.4 mix for enhanced functionality

After being familiar with Laravel 5.1 mix (elixir), I decided to give Laravel 5.4 mix a try. I combined my libraries into vendor files. mix .styles([ './node_modules/bootstrap/dist/css/bootstrap.css', './node_modules/font-awesome/c ...

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

I'm wondering if anyone has any insights as to why the CSS rule `body{ overflow: auto;}` is not functioning properly for me. Despite my attempts of adding a class to the body tag and

I am facing an issue where adding body tags to my code in Visual Studio code does not yield the desired results. Interestingly, it doesn't seem to be a syntax error in CSS. body{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI&apo ...

Switch back JSON in php script

After receiving a JSON object with an unspecified number of key/value pairs, I need to send it from my $.ajax function to a PHP script. The PHP script must then revert the JSON object and send it back to jQuery. {"First name": "John", "Contact": "2323",.. ...

Error with Vimeo SDK: Mysterious Player Issue Post Setup (VueJS)

I have a requirement to showcase multiple videos on a Vue-powered website using a Vimeo player. To achieve this, I have developed a VideoPlayer component specifically designed for each video: <template> <div class="video-element__containe ...