最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger html5 input datalist dropdown to show up - Stack Overflow

programmeradmin1浏览0评论

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>

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>

Share Improve this question asked Jan 17, 2015 at 2:42 laggingreflexlaggingreflex 34.7k36 gold badges144 silver badges200 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论