繁体   English   中英

如果输入框中没有文本,如何显示html5 datalist元素的所有选项?

[英]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") - - 但正如您所发现的, ArrowDownArrowUp存在一个例外,它具有我无法通过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM