FIlter not happening in html list

I am creating one list on click of an input tag. Now I want to be the filter data when I type in the input tag and the taht happens, but after selecting one of the data, the filtering does not happen from the second data forward.

Code for my filter.

function filterList(value, list) {
        var li, i, match;

        for (i = list.children.length; i--;) {
            li = list.children[i];
            match = li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1;
            li.classList.toggle('hidden', !match)
        }
    }

      

Here are a few of the problems I ran into. Can anyone help me resolve this. I created a fiddler where everything works and you can see the problem. Fiddle

  • No filter is executed for second data ahead.
  • Put some data from the key and then select some value from the list, both values ​​will be achieved.
+3


source to share


2 answers


you added a space between the quotes

li[i].style.display = " ";

so just remove that space, it will work fine

li[i].style.display = "";

      




as you are planning to add the selected fields to the input field
( which is some thing like how you add tags in stackoverflow

or some other sites)

you can find a similar answer here
and read the comments there as some have mentioned GitHub related libraries

+2


source


Ok ... let's say you have a lot of problems with your code.

First of all, always hold your console.

for (i = list.children.length; i--;) {
    li = list.children[i];
    match = li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1;
    li.classList.toggle('hidden', !match)
}

      

Your loop for

has already started outside the array index. Not to mention the fact that you put the stepping part into the conditional part.

Using it for.. of

instead works much better in this case.




Second, you are applying a class to the li, which has no effect because you haven't defined it in the css.

Third, I'm not sure why you add show / hide logic inside the openList function, it doesn't make sense.

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

      

Here's a working / updated fiddle. https://jsfiddle.net/kLaeyt5L/2/

0


source







All Articles