Reputation: 359
I have a text input with a datalist that's dynamically populated as the user types. This seems to work - as I type I see in the DOM inspector that the datalist
element is being populated with option
s. However, the dropdown box that should let the user select an option
doesn't appear. Is there some javascript I can use to force it to appear?
<html>
<body>
<input type="text" name="brand" id="brand_input" list="brand_list" oninput="handleInput(this)" placeholder="Brand">
<datalist id="brand_list"></datalist>
</body>
<script>
window.addEventListener("load", function() {
window.inputXHR = new XMLHttpRequest();
});
function handleInput(input) {
var list = input.list;
window.inputXHR.abort();
window.inputXHR.onreadystatechange = function() {
if (window.inputXHR.readyState === XMLHttpRequest.DONE) {
var status = window.inputXHR.status;
if (status == 0 || (status >= 200 && status < 400)) {
list.innerHTML = "";
var resp = JSON.parse(window.inputXHR.responseText);
resp.forEach(function(i) {
var opt = document.createElement("option");
opt.value = i;
list.appendChild(opt);
});
// These two lines fix the issue:
document.getElementById("otherelement").focus();
input.focus();
}
}
};
window.inputXHR.open("GET", "/get_brand/"+input.value, true);
window.inputXHR.send();
}
</script>
</html>
e: I found that focusing away from the textbox and then re-focusing fixes the issue. I added a couple lines in my code above that do that automatically after the datalist is loaded.
Upvotes: 0
Views: 160
Reputation: 2247
Do not know how/where you get your data, but code seems to work using fake demo data ?
window.addEventListener("load", function() {
window.inputXHR = new XMLHttpRequest();
});
function handleInput(input) {
var list = input.list;
window.inputXHR.abort();
window.inputXHR.onreadystatechange = function() {
if (window.inputXHR.readyState === XMLHttpRequest.DONE) {
var status = window.inputXHR.status;
if (status == 0 || (status >= 200 && status < 400)) {
list.innerHTML = "";
var resp = JSON.parse(window.inputXHR.responseText);
resp.forEach(function(i) {
var opt = document.createElement("option");
opt.value = i;
list.appendChild(opt);
});
}
}
};
window.inputXHR.open("GET", "/get_brand/"+input.value, true);
window.inputXHR.send();
}
// Mock demo here
window.addEventListener("load", function() {
window.inputXHR = {
readyState: XMLHttpRequest.DONE,
status: 200,
responseText: '["Charles Rolls","Henry Royce"]',
abort: function(){},
open: function(){},
send: function(){this.onreadystatechange();}
}});
<input type="text" name="brand" id="brand_input" list="brand_list" oninput="handleInput(this)" placeholder="Brand">
<datalist id="brand_list"></datalist>
Upvotes: 1