15

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>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it's not working on the touch keyboard, why? should I send a keypress trigger? I want open list when clicking touch keyboard keys
I ended up doing this (alas a jquery fix): $(element).trigger(jQuery.Event('keyup', { keycode: 40 }));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.