Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
How do I display an error message if there is no valid result matching the search?

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 class="search-results" 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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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";
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

why not declare the variable for search-results and add an if statement inside the for loop!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda