简体   繁体   中英

how to display all the options of a html5 datalist element when there is no text in the input box?

I want to display all the options available within the datalist element when length of the text input equals 0. I have tried firing a down arrow keypress event but somehow that gets overridden every time. I had read somewhere that , on focus of the input, on down key arrow press, the dropdown reveals all the options. Was trying to mimic that behaviour through this code This is the input box to which the options get appended dynamically:

<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();
        }
    }

You can "display" the option values when the input gets the focus like in this snippet. (From your code it looks like you just want to log each one.)

As alternatives to the focusin event, you could run the function on the input event -- or if you want to run it on each keystroke, keyup worked fine for me too (eg: if(event.code == "ArrowRight") -- but as you discovered, an exception exists for ArrowDown and ArrowUp , which have default behavior (in Chrome, anyway) that I could not prevent with 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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