skip to Main Content

I’m trying to create logic for my search bar to search through elements by their IDs, but it’s not working. As can be seen in the HTML code, the elements contain pictures. That’s why I’m using this method to display the elements.

here is the HTML code:

<html>
<html lang="en">

<head>
    <title>BONIXS</title>
    <link rel="shortcut icon" href="BONIXS.ico" type="image/x-icon">
    <link rel="stylesheet" href="Ghost Runner.css">
</head>

<body>
    <div>
        <a href="D:/VSCODE/STEAM.html" id="Start">BONIXS</a>
    </div>
    <div> 
    <img src="Ghosrunner.png" alt="Ghost Runner" id="Ghostrunner">
    </div>
    <div class="Download">
    <a href="Ghost Runner.zip" download>
        <button class="Download-button">Download</button>
    </a>
    </div>
</body>
</html> 

and here is the JavaScript logic code for it:

const searchBar = document.getElementById('searchBar');
const searchResults = document.getElementById('searchResults');

searchBar.addEventListener('keyup', function(event) {
  console.log('Keyup event detected'); // Check if event listener is triggered

  if (event.key === 'Enter') {
    const searchTerm = searchBar.value.toLowerCase();
    console.log('Search term:', searchTerm); // Check the search term

    searchResults.innerHTML = '';

    const matchingResults = performSearch(searchTerm);
    console.log('Matching results:', matchingResults); // Check the matching results

    displayResults(matchingResults);
  }
});

function performSearch(searchTerm) {
  const allElements = document.querySelectorAll('[id]');
  return Array.from(allElements).filter(element => element.id.toLowerCase().includes(searchTerm));
}

function displayResults(results) {
  results.forEach(result => {
    const li = document.createElement('li');
    li.textContent = result.id;
    searchResults.appendChild(li);
  });
}

I tried multiple times but it didn’t work

2

Answers


  1. You can wrap the input in a form to get "Enter" functionality.

    Note: Tyr typing "or" andpressing Enter

    const searchForm = document.getElementById('search-form');
    const searchResults = document.getElementById('search-results');
    
    const handleSubmit = (e) => {
      e.preventDefault();
      const searchTerm = e.target.elements.term.value.toLowerCase();
      console.log('Search term:', searchTerm); // Check the search term
      searchResults.innerHTML = ''; // Clear existing results
      const matchingResults = performSearch(searchTerm);
      console.log('Matching results:', matchingResults); // Check the matching results
      displayResults(matchingResults);
    };
    
    const performSearch = (searchTerm) =>
      [...document.querySelectorAll('[id]')]
        .filter(element => element.id.toLowerCase().includes(searchTerm));
    
    const displayResults = (results) => {
      searchResults.innerHTML = '';
      results.forEach(result => {
        const li = document.createElement('li');
        li.textContent = result.id;
        searchResults.appendChild(li);
      });
    };
    
    searchForm.addEventListener('submit', handleSubmit);
    body { padding: 0.25rem; }
    h2 { margin: 0; }
    ul { padding: 0.5rem 0 0 1.25rem; margin: 0; }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"/>
    <form id="search-form" autocomplete="off">
      <input type="search" id="search-term" name="term" placeholder="Search...">
    </form>
    <hr />
    <h2>Examples</h2>
      <span id="apple">Apple</span>,
      <span id="ape">Ape</span>,
      <span id="orange">Orange</span>,
      <span id="orangutan">Orangutan</span>
    <hr />
    <h2>Results</h2>
    <ul id="search-results"></ul>
    Login or Signup to reply.
  2. Your code is working as expected. There are no IDs elements in your HTML. Try to type for example "Ukraine" and you’ll see matching results.

    const searchBar = document.getElementById('searchBar');
    const searchResults = document.getElementById('searchResults');
    
    searchBar.addEventListener('keyup', function(event) {
      console.log('Keyup event detected'); // Check if event listener is triggered
    
      if (event.key === 'Enter') {
        const searchTerm = searchBar.value.toLowerCase();
        console.log('Search term:', searchTerm); // Check the search term
    
        searchResults.innerHTML = '';
    
        const matchingResults = performSearch(searchTerm);
        console.log('Matching results:', matchingResults); // Check the matching results
    
        displayResults(matchingResults);
      }
    });
    
    function performSearch(searchTerm) {
      const allElements = document.querySelectorAll('[id]');
      return Array.from(allElements).filter(element => element.id.toLowerCase().includes(searchTerm));
    }
    
    function displayResults(results) {
      results.forEach(result => {
        const li = document.createElement('li');
        li.textContent = result.id;
        searchResults.appendChild(li);
      });
    }
    <ul style="display: none;">
        <li id="Ukraine">Ukraine</li>
        <li id="United States">United States</li>
        <li id="Japan">Japan</li>
    </ul>
    <input type="text" id="searchBar" placeholder="Search...">
    <ul id="searchResults"></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search