javascripthtmlsearchsearchbar

search bar that updates after every letter inputted html and javascript


So I have a site that has a ton of buttons, but I want to make a search bar that after every letter, it compares the contents with the id or alt of each button, so basically if I type “he”, it will show all things that have “he” in the first 2 letters of their name and not show the others

Anyone know how I would be able to do something like that?

I tried making a form that compares it when I click the submit button, but I cant seem to figure out how to make it so it updates after every letter, and I also cant figure out how to compare it properly either as it just didnt update anything: <input id="Search"></input> <button class="searchItem", id="123">123</button> <button class="searchItem", id="122">122</button> <button class="searchItem", id="213">213</button>

 const SearchBar = document.getElementById("Search");

SearchBar.addEventListener("input", updateValue);

function updateValue(e) {

const searchItems = document.getElementsByClassName("searchItem");
[searchItems].forEach(el => { 
  
  if (el.id.startsWith(e.value)) {
    el.style.display = 'block';
    print('what ok')
  } else {
    el.style.display = 'none';
    print('doesnt work')
  }
 });
};

 

Solution

  • e in your event callback is the input event object, but you want instead e.target.value to get the current value of the <input>:

    function updateValue(e) {
      ...
      if (el.id.startsWith(e.target.value) { 
        ... 
      }
    }