I'm making a search bar and this is my JavaScript code so far:
function search_product() {
var searchbar, filter, cards, card, h1, i, txtValue;
searchbar = document.getElementById('searchbar');
filter = searchbar.value.toUpperCase();
cards = document.getElementById("cards");
card = cards.getElementsByClassName('card');
searchbar.addEventListener("keyup", function (event) {
if (event.key === 'Enter') {
event.preventDefault();
for (i = 0; i < card.length; i ) {
h1 = card[i].getElementsByTagName("h1")[0];
txtValue = h1.textContent || h1.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
card[i].style.display = "";
}
else {
card[i].style.display = "none";
}
}
}
})
}
Basically searching for the content of the h1 tag. Everything works fine, but I want to add an error message if there are no matching results, so I just made this HTML and CSS:
HTML
<div id="search-results">
<h1>No results found.</h1>
<p>That resource does not exist.</p>
<img src="../img/icons/animated/passaros.gif">
</div>
CSS
.search-results {
background-color: #131313;
height: 48vh;
border-radius: 5px;
text-align: center;
padding: 15px;
display: none;
}
.search-results h1 {
margin: 0;
color: #ffffff;
}
.search-results p {
margin: 0;
color: #cccccc;
}
And made it hidden. I know how to make it a block using JS:
document.getElementById("search-results").style.display = "block";
But I don't know where to put this line in the JS, because in the first "if" I basically check if the input is empty and make all the cards re-appear if it is, and in the "else" return the matching results.
Thx to anyone that helps in advance.
CodePudding user response:
There are multiple ways to identify no result found, as per your code, simplest way to add with a flag, let's say flag name resultFound
like
var resultFound;
for (i = 0; i < card.length; i ) {
h1 = card[i].getElementsByTagName("h1")[0];
txtValue = h1.textContent || h1.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
resultFound = true;
card[i].style.display = "";
} else {
card[i].style.display = "none";
}
}
if(resultFound) {
document.getElementById("search-results").style.display = "";
} else {
document.getElementById("search-results").style.display = "block";
}
CodePudding user response:
why not declare the variable for search-results and add an if statement inside the for loop!