[英]how to display all the options of a html5 datalist element when there is no text in the input box?
当文本输入的长度等于0时,我想显示datalist元素中的所有可用选项。我尝试触发向下箭头按键事件但不知何故每次都被覆盖。 我已经阅读了某个地方,在输入的焦点上,按下向下箭头键,下拉列表显示所有选项。 试图通过此代码模仿该行为这是动态附加选项的输入框:
<input class="chosen-select-zone-start-end grey-placeholder" onkeyup="showHint(event, this.value)" id="start-zone-flowInput" list='start-zone-list' placeholder="Select Start Zone" autocomplete="on" />
function clickevent(){
var e = $.Event("keydown");
e.which = 40;
e.keyCode = 40;
console.log("evetn", e);
$("#start-zone-flowInput").focus().trigger(e);
// $("#start-zone-flowInput")
e.preventDefault();
}
function showHint(event, val) {
console.log(val, val.length);
if(val.length === 0) {
console.log("firing event .....");
clickevent();
}
}
您可以在输入获得焦点时“显示”选项值,就像在此片段中一样。 (从你的代码看起来你只想记录每一个。)
作为focusin
事件的替代方案,您可以在input
事件上运行该函数 - 或者如果您想在每次击键时运行它, keyup
也适用于我(例如: if(event.code == "ArrowRight")
- - 但正如您所发现的, ArrowDown
和ArrowUp
存在一个例外,它具有我无法通过event.preventDefault()
阻止的默认行为(无论如何在Chrome中event.preventDefault()
。
const options = document.querySelectorAll("#start-zone-list > option"); document.addEventListener("focusin", logOptions); function logOptions(event){ if(event.target.id == "start-zone-flowInput" && event.target.value == ""){ for(let option of options){ console.log(option.innerHTML); } } }
<input class="chosen-select-zone-start-end grey-placeholder" id="start-zone-flowInput" list='start-zone-list' placeholder="Select Start Zone" autocomplete="on" /> <datalist id="start-zone-list"> <option>a</option> <option>b</option> </datalist>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.