Search code examples
javascriptfor-loopsearchbar

For loop over Array is not working. how to fix it?


I want to create a searchbar on a website. It should update the content while you are typing. With an if statement it is working. But the for loop causes problems.

var shoplist = ["1", "2", "3"];
var shoplistlength

function hid(event) {
  event.preventDefault();
  shopsuche = document.getElementById("search").value;

  for (var i = 0; i < shoplistlength; i++) {
    if (shoplist[i].includes(shopsuche)) {
      document.getElementById("2").children[i].style.display = "inline"
    }
  }
}

The inputfield:

<input class="form-control mr-sm-2"
                    type="search"
                    placeholder="What you are looking for?"
                    aria-label="Search"
                    name="search"
                    id="search"
                    onkeyup="hid(event)"
                    >

I want to minimize the code through the for-loop. I will check each variable in the shoplist and then i will check if the shopsuche contains letters from the list. If yes the site should show a list element. I will get the ul list child with the variable i because the shoplist is build like the list.

Update:

I deleted shoplistLength and replaced it with the number. I know its not the best way but I try to understand my mistake. I think something with my array is wrong. If I do this:

 var shoplist = ["1", "2", "3"];
 function hid(event){
 ... 
 for (var i = 0; i < 3; i++){
     if ("1".includes(shopsuche)) { 
       document.getElementById("2").children[i].style.display="none"} 

I get the expected result. However, if I use the array and index:

if (shoplist[i].includes(shopsuche)) { 

then the site remains the same.


Solution

  • As Jbluehdorn points out, you haven't initiated the shoplistlength.

    For cleaner and more readable code, I would suggest using the forEach method when looping through arrays:

    var shoplist = ["1", "2", "3"]
    
    function hid(event) {
      event.preventDefault()
      shopsuche = document.getElementById("search").value
    
      shoplist.forEach((shop, i) => {
        if (shop.includes(shopsuche)) {
          document.getElementById("2").children[i].style.display = "inline"
        }
      }
    }