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

300
Visualizações
Hide datalist when single value left

When there is only one item left in datalist, I want to autocomplete input and hide datalist. I can achieve this last behaviour changing the id as shown here. However, it seem too brutal, and also throw some errors in the console (although it works). Is there a more elegant way of hiding a datalist?

Sample code below and in this fiddle.

$(document).on('keyup', '#CarsInput', function(){
    UpdateDropDown('CarsInput', 'Cars');
});

function UpdateDropDown(idInput, idlist) {
  var datalist = document.getElementById(idlist);
  var options = datalist.getElementsByTagName('option');
  var search = document.getElementById(idInput);
  search.oninput = function () {
    var n_matches = 0;
    var Seleccionado;
    for(var i = 0; i < options.length; i++) {
      if (options[i].value.toLowerCase().includes(search.value.toLowerCase())) {
        n_matches++;
        if (n_matches===1) {
          Seleccionado=options[i].value;

        }
        else {
          Seleccionado='';

        }
      }
    }       
    if (n_matches===1) {
      $("#"+search.id).val(Seleccionado);
      //HERE! is there a more elegant way?
      datalist.id = "";    
    }
    else {
      //HERE! is there a more elegant way?
      datalist.id = idlist;    
    }
  };
}
.GeneralInputs {
  margin-top: 2rem;
  margin-left: 2rem;
    padding: 0.2rem 0.4rem;
    border: 1px solid #E5E3E3;
    border-radius: 6px;
  width: 200px;
    outline: none;
    transition: all 0.3s ease-out;      
}

.GeneralInputs:focus {
    border: 1px solid #900;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="search" list="Cars" class="GeneralInputs" id="CarsInput" onclick="this.select();" placeholder="car name here..."/>
<datalist id="Cars">
  <option value="Volvo"/>
  <option value="Volkswagen"/>
  <option value="Mitsubishi"/>
  <option value="Mini"/>
  <option value="Ford"/>
</datalist>

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