'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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
