Hello Everyone
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
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: