When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active.

I could really use some help with this as it's starting to get on my nerves.

(I've removed the CSS, but you can still visualize it quite well, thanks!)

var myInput = document.getElementById('myInput');


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

var h2 = document.getElementById('hh');
h2.addEventListener('click', clear);

function clear() {
    myInput.value = '';
}
<h2 id="hh">Click here to empty input</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>

Answer №1

It's not the filter itself that is directly applied, but rather the consequences of applying it.

Upon reviewing your code, you will notice that at one point, you have set the <li> elements that did not match your filter criteria to display: none.

The clear() function resets the input value without reversing the changes made to the <li> elements that were hidden by setting display: none.

To fully clear the filter, your clear() function should also remove the display: none from all <li> elements in the array by iterating through the array and undoing the changes made to the display property.


        const myInput = document.getElementById('myInput');
        const ul = document.getElementById("myUL");
        const list = ul.children
        
        function myFunction() {
            // Function code here
        }
        
        var h2 = document.getElementById('hh');
        h2.addEventListener('click', clear);
        
        function clear() {
            // Clear function code here
        }
    

It is advisable to use ul.children instead of ul.getElementsByTagName("li"), as children of an <ul> element are essentially <li> elements.

The provided code successfully clears out the filter as intended. I recommend using const or let instead of var for better variable management and error prevention in your code.

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

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

Creating input fields using Bootstrap HTML on a single line

Struggling with Bootstrap, I can't figure out how to display the following HTML inputs in a single line: <div class="row"> <div class="col-sm-8"> <div class="form-group"> <input class="form-control" ...

Issues with the CSS code causing the dropdown menu to malfunction

Having trouble getting my CSS to apply when creating a drop-down menu. I've set up UL and LI elements for the dropdown, but the styling is not rendering as expected. Check out the screenshot below for a look at how it currently appears using developer ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

Is there a way to deactivate the dot key using the keyup event in Vue.js 2?

My current approach is as follows: <template> ... <input type="number" class="form-control" v-model="quantity" min="1" v-on:keyup="disableDot"> ... </template> <script> export default{ ... methods:{ ...

Can you explain the function of a digest attribute?

As a beginner in the world of NextJS, I am currently working on getting my first project ready for production. However, I encountered the following error: Application error: a client-side exception has occurred (see the browser console for more information ...

Verifying that a parameter is sent to a function triggering an event in VueJS

One of the components in my codebase is designed to render buttons based on an array of objects as a prop. When these buttons are clicked, an object with specific values is passed to the event handler. Here's an example of how the object looks: { boxe ...

Click on the div to automatically insert its text into the textarea

I am looking for a way to enable users to edit their posts easily. My idea is to have them click on a link, which will then hide the original div containing their post and reveal a new div with the old text inside a textarea for editing. Despite searching ...

What is the method for displaying an array in JavaScript?

When a user clicks the value 3 input box, three input boxes will appear where they can enter values. However, when trying to submit the array, no elements are printed and an error message "Element is not defined" appears. var arr = [0]; function get_va ...

Tips for expanding an input to fit the width of a div without altering the dimensions of a preceding span element

Let me explain, I have a form that includes a span and an input: <form onSubmit={e => handleSubmit(e)}> <Box className='form_box'> <span> <a href="/cd ...

Error Message: Namespace Invalid in Node.js Application Utilizing Mongoose Library with MongoDB Atlas Database

I've been working on a Node.js application similar to Twitter, utilizing Mongoose (version 8.0.2) to communicate with a MongoDB Atlas database. However, I'm stuck dealing with an error message that reads MongoServerError: Invalid namespace specif ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

PHP updating data in a MySQL database

I've been using easyPHP and encountering issues with updating records in my database. Whenever I try to update, the HTML form displays and instead of updating the data. However, it does print "Updated dat ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Is it possible to adjust positioning using just CSS?

I'm attempting to arrange these elements as shown in the image below: https://i.stack.imgur.com/tWy1I.png https://jsfiddle.net/ut1mgcLb/ HTML <div class="object1"> <div class="snax-voting-container-body"> ...

Maintaining the image's aspect ratio using the Next Image component

Currently, I am using Next's Image component to display a logo. Although the image itself is 1843x550 px, I have specified the width and height properties to adjust it to fit within a space of 83x24 px. However, due to a slightly different aspect rati ...

Bring in a JavaScript file from Blogger without using a tag

Is there a way to retrieve blogger feeds code without using