Looking for a solution to toggle the visibility of a div based on whether search results are found or not using JavaScript

Running this code

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Search Bar</title>
</head>

<body>

   <style>

ul#wrapper {
    padding: 10px;
    list-style: none;
    display: none;
}


#result {
    display: none;
}

</style>


<script>

function searchFunction() {

var ape=document.getElementById("myinput");

  var xpe = ape.value;
if (xpe.length<1) {
    alert("The search field is empty!");
    return false;
  }

 else if (xpe.length<3) {
    alert("Minimum of 3 characters required for search");
    return false;
  }


var input, filter, ul, li, a, i;
    input = document.getElementById('myinput');
    filter = input.value.toUpperCase();
    ul = document.getElementById('wrapper');
    fp = document.getElementById('fullpage');
    result = document.getElementById('result')
    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 = "";
            ul.style.display = "block";
            fp.style.display = "none";
            result.style.display = "none";
        }
        else{
            li[i].style.display = "none";
            result.style.display ="block";
        }
    }
}

</script>

        <input type="text" name="search" value="" autocomplete="off" id="myinput" placeholder="Search" />

<button onclick="searchFunction()"> search </button>
<br/><br/>


<div id="result"> No results found! </div>

    <ul id="wrapper">
        <li>
            <a href="#">Apple</a>
        </li>
        <li>
            <a href="#">Ball</a>
        </li>
        <li>
            <a href="#">Cat</a>
        </li>
        <li>
            <a href="#">Dog</a>
        </li>
        <li>
            <a href="#">Elephant</a>
        </li>
        <li>
            <a href="#">Fish</a>
        </li>
        <li>
            <a href="#">Grape</a>
        </li>
        <li>
            <a href="#">Horse</a>
        </li>
        <li>
            <a href="#">Ice-Cream</a>
        </li>
        <li>
            <a href="#">Joker</a>
        </li>
        <li>
            <a href="#">Kite</a>
        </li>
        <li>
            <a href="#">Lion</a>
        </li>
        <li>
            <a href="#">Mango</a>
        </li>
        <li>
            <a href="#">Nest</a>
        </li>
        <li>
            <a href="#">Orange</a>
        </li>
        <li>
            <a href="#">Parrot</a>
        </li>
        <li>
            <a href="#">Queen</a>
        </li>
        <li>
            <a href="#">Rat</a>
        </li>
        <li>
            <a href="#">Ship</a>
        </li>
        <li>
            <a href="#">Table</a>
        </li>
        <li>
            <a href="#">Umbrella</a>
        </li>
        <li>
            <a href="#">Violet</a>
        </li>
        <li>
            <a href="#">Watch</a>
        </li>
        <li>
            <a href="#">X-max</a>
        </li>
        <li>
            <a href="#">Yatch</a>
        </li>
        <li>
            <a href="#">Zebra</a>
        </li>
    </ul>

<div id="fullpage">
This is a full page content that hides when the search button is clicked for future usage.
<div>

</body>
</html>

Expected Output:

When the search button is clicked and a matching search input is found in the list, the list should be displayed. If there are no matches in the list, a div containing "No results found!" should be displayed. When the user searches for a suitable keyword that matches the list, the div should hide and only show the search results.

I have tried using display: none; in CSS and block in JS. Unfortunately, it did not work as expected. I was thinking about using toggle, but I am a beginner in JS. How can I fix this issue? Any help with solutions would be greatly appreciated.

Answer №1

Attempting to conceal the message "No results found !" within a for loop, but failing to terminate the loop once a match is found.

A revised code structure could look like this ↓↓

<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Search Bar</title>

    <style>
        ul#wrapper {
            padding: 10px;
            list-style: none;
            display: none;
        }

        #result {
            display: none;
        }
    </style>

</head>

<body>

<script>
function searchFunction() {
    var inputField = document.getElementById("myinput");
    var searchText = inputField.value;
    
    if (searchText.length < 1) {
        alert("Search field empty !");
        return false;
    } else if (searchText.length < 3) {
        alert("Minimum of 3 characters required for search");
        return false;
    }

    var input, filter, ul, li, a, i;
    input = document.getElementById('myinput');
    filter = input.value.toUpperCase();
    ul = document.getElementById('wrapper');
    fp = document.getElementById('fullpage');
    result = document.getElementById('result')
    li = ul.getElementsByTagName('li');

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

    if (foundMatches === 0) {
        fp.style.display = "none";
        result.style.display = "block";
    }
}
</script>

<input type="text" name="search" value="" autocomplete="off" id="myinput" placeholder="Search" />
<button onclick="searchFunction()"> Search </button>
<br/><br/>

<div id="result"> No results found ! </div>

    <ul id="wrapper">
        <li>
            <a href="#">Apple</a>
        </li>
        <li>
            <a href="#">Ball</a>
        </li>
        
        <!-- Remaining list items omitted for brevity -->

    </ul>

<div id="fullpage">
Content for full page that gets hidden when search button is clicked, intended for future use.
<div>

</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

Enhance the appearance of datatables pagination with a personalized touch

I am working on a page that utilizes server-side datatables and I want to implement a custom pagination style on it: HTML <ul class="pagination pagination-danger"> <li class="page-item"><a class="page-link" href="#" data-original-title ...

Step by step guide on serializing two forms and an entire table

I have been attempting to serialize data from two forms and the entire table simultaneously. While the form data is successfully serialized, I am encountering difficulty in serializing the table records as well. Below is the code snippet of what I have att ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...

`Can you guide me on the proper path for designing this website layout?`

As I embark on creating my first website, I have a specific vision in mind. I want the full display on a computer screen to show all the information and links without any need for scrolling. However, when the window is resized to smaller screens, I would l ...

How to Override Global CSS in a Freshly Created Angular Component

My CSS skills are a bit rusty and I need some assistance with a project I'm working on. The project includes multiple global CSS files that have properties defined for different tags, such as .btn. However, these global CSS files are causing conflicts ...

Troubleshooting Browser Behavior: Back Button Not Loading Page - jQuery and HTML5

I've built a dynamic slideshow using jQuery to change images with seamless transitions. To enhance user experience, I'm also updating the page title and URL without triggering a page reload. The code snippet below illustrates how I achieve this: ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Run JavaScript code whenever the table is modified

I have a dynamic table that loads data asynchronously, and I am looking for a way to trigger a function every time the content of the table changes - whether it's new data being added or modifications to existing data. Is there a method to achieve th ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

Several radio buttons and their corresponding labels are shown on a single line inside a nested div container

Upon stumbling across this post, I realized it perfectly aligns with my current goal: Radio Button and Label to display in same line. However, the challenge persists... The layout I currently have (first 3 columns) differs from what I aspire to achieve (l ...

In Safari, non-ascii characters are incorrectly stored in document.cookies as trash

Below is a snippet of JavaScript code that I am working with: wdata['account'] = {"value": $(input).val(), "title": "Номер карты получения"}; var r = { "ipayway": ipw_selected, "wpayway": wpw_selected, "amount_type" ...

Please insert a border shade on my navigation bar

I have been attempting to add a special effect to my menu. Specifically, I have been trying to include a 3px border at the top of each "li" element in my menu that only appears when hovered over. Unfortunately, my attempts using :after pseudo-selector hav ...

Node.js refusing to acknowledge the get request handler for the homepage of the website

My Node.js server setup is quite simple: const express = require('express'); const app = express(); const http = require("http"); const path = require('path'); const favicon = require('serve-favicon'); // Public fil ...

Exploring the features of AngularJS, one can delve into the ControllerAs syntax

Currently, I am in the process of developing a directive and following the guidelines outlined in the John Papa style guide. In line with this, I have adopted the ControllerAs syntax approach and implemented a small directive as shown below: (function() { ...

Sorting Angular data using database queries

I'm currently setting up a blog for my website. Everything is running smoothly with the database, but I've run into an issue with the order of my posts - they are displayed in the opposite order that I want. The oldest post is showing at the top, ...

What is the best way to add a multiselect option in Django to display detailed information for each selected item

Experience the Description Image I am looking to develop a mini demonstration similar to the image provided. When I click on an item in the left column to select a country, I want the right column to dynamically display all the cities of the chosen countr ...

Unable to load JQuery from a div element

My goal is to create a standard .html file containing the navigation, footer, and other elements that will be used across multiple pages for a small site I'm building. I want to keep it simple and avoid using php or other programming languages. I&apo ...

Turn off automatic zooming for mobile device input

One common issue observed in mobile browsers is that they tend to zoom in on an input field or select drop-down when focused. After exploring various solutions, the most elegant one I came across involves setting the font-size of the input field to 16px. W ...