Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger html5 input datalist dropdown to show up

In an HTML5 <input> element with pre-defined values in a <datalist>, when user either enters a matching value or hits the down key, the dropdown list shows up.

Is there a way to trigger this dropdown list to show up? I might change the datalist dynamically in Angular, and so would like to have a way to trigger the showing up of this list.

  <input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
like image 632
laggingreflex Avatar asked Jan 17 '15 02:01

laggingreflex


Video Answer


1 Answers

Yes we can:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

keyboardEvent[initMethod](
  "keyup", // event type : keydown, keyup, keypress
  true, // bubbles
  true, // cancelable
  window, // viewArg: should be window
  false, // ctrlKeyArg
  false, // altKeyArg
  false, // shiftKeyArg
  false, // metaKeyArg
  40, // keyCodeArg : unsigned long the virtual key code, else 0
  0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.getElementById("test").focus();
document.getElementById("test").dispatchEvent(keyboardEvent);
<input id="test" list="browsers" name="browser">
<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

Using dispatchEvent and createEvent. Supported by IE9+, Chrome and FF.

like image 176
Mouser Avatar answered Sep 20 '22 20:09

Mouser