[英]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.