My Search Results Wont Empty

Hello Everyone :slight_smile:

Hi so I have successfully implemented a search results in my test website, now the only last step is that it wont clear when nothing is entered in the search bar. Please help :frowning:

My JS Code:

console.log('Heelowwww');

const url = 'http://localhost:8000/';

const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');
const resultsBox = document.getElementById('results-box');

const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value;

options = {
  method: 'GET',
  headers: {
    Accept: 'application/json',
  },
  data: {
    csrfmiddlewaretoken: csrf,
  },
};

const SearchPosts = async (SearchIt) => {
  const res = await fetch('http://localhost:8000/data/', options);
  const Posts = await res.json();

  const regex = new RegExp(`^${SearchIt}`, 'gi');

  resultsBox.innerHTML = '';

  for (var i = 0; i < Posts.data.length; ++i) {
    if (Posts.data[i].title.match(regex)) {
      // var htmlstring = ""
      resultsBox.innerHTML += `<a href = "${url}${Posts.data[i].slug}" target="_blank">
		<b>${Posts.data[i].title}</b>
		</a>
		<img class="rounded-circle account-img"src = "${Posts.data[i].image}">`;
      console.log(Posts.data[i].title);
    }
  }
};

searchInput.addEventListener('input', () => {
  SearchPosts(searchInput.value);
  if (resultsBox.classList.contains('not-visible')) {
    resultsBox.classList.remove('not-visible');
  }
});

My Results Page:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I’m not sure I understand this.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.