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

217
Visualizações
Vanilla JavaScript search - how to show results only when button is clicked?

I'm using this function to fetch a JSON with data to be searched. Now, as soon as someone type the keywords a list of relative data is immediately shown. I'd like to show the results only when button is clicked. But I cannot find a way.

document.addEventListener('DOMContentLoaded', function(event) {
  const search = document.getElementById('search');
  const results = document.getElementById('results');
  let data = [];
  let search_term = '';

  fetch('/search.json')
    .then(response => response.json())
    .then(data_server => {
      data = data_server;
    });

  search.addEventListener('input', event => {
    search_term = event.target.value.toLowerCase();
    showList();
  });

  const showList = () => {
    results.innerHTML = '';
    if (search_term.length <= 0) return;
    const match = new RegExp(`${search_term}`, 'gi');
    let result = data.filter(name => match.test(name.title) || match.test(name.meta_description) || match.test(name.tags));
    if (result.length == 0) {
      const li = document.createElement('li');
      li.innerHTML = `No results found`;
      results.appendChild(li);
    }
    result.forEach(e => {
      const li = document.createElement('li');
      li.innerHTML = `<a href="${e.url}">${e.title}</a><br>${e.meta_description}`;
      results.appendChild(li);
    });
  };
});

And this is the search input:

            <input autocomplete="off" type="search" id="search" placeholder="Search">
            <button type="submit">Search</button>
            <ul id="results"></ul>
about 4 years ago · Juan Pablo Isaza
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