Home > other >  How to search a json file from a search bar in html?
How to search a json file from a search bar in html?

Time:11-11

I am working on a project that requires a search bar on a website that would search through a (hopefully) JSON file. It doesn't have to be json, but it needs to be able to store other information about an object. This is what I have right now,

function search_animal() {
    let input = document.getElementById('searchbar').value
    input=input.toLowerCase();
    let x = document.getElementsByClassName('room');
    
  //input = the input in the search bar
  //x = the list of elements
  
    for (i = 0; i < x.length; i  ) {
        if (!x[i].innerHTML.toLowerCase().includes(input)) {
            x[i].style.display="none";
      
        }
    
        else {
            x[i].style.display="list-item";             
        }
    }
}
<input id="searchbar" onkeyup="search_animal()" type="text"
        name="search">

I can't figure out how to make results pop up while typing, and how to display the object with other characteristics in addition to the name

CodePudding user response:

Let's suppose you have a real JSON (stringified), each object of this json array represents one animal.

first of all we parse the JSON to a javascript array of objects with JSON.parse()

Now, your function that searches is almost perfect for your use case, but since your example didn't show what .room is, I just created an HTML <ul> that will hold the dynamic created list items.

In the for, get each object and verify if the Name includes what is being searched. If yes, create a <li> and add any content/HTML to it and then append this new list item to your <ul>

See if below code is similar to what you need

let jsonData = `[
  {"Name": "Lion", "Color": "Yellow"},
  {"Name": "Monkey", "Color": "Orange"},
  {"Name": "Fish", "Color": "Blue"},
  {"Name": "Cat", "Color": "Black"}
]`

let data = JSON.parse(jsonData)

function search_animal() {
  let input = document.getElementById('searchbar').value
  input = input.toLowerCase();
  let x = document.querySelector('#list-holder');
  x.innerHTML = ""

  for (i = 0; i < data.length; i  ) {
    let obj = data[i];

    if (obj.Name.toLowerCase().includes(input)) {
      const elem = document.createElement("li")
      elem.innerHTML = `${obj.Name} - ${obj.Color}`
      x.appendChild(elem)
    }
  }
}
<input id="searchbar" onkeyup="search_animal()" type="text" name="search">

<ul id="list-holder">

</ul>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related