1

I am trying to click a button that will trigger a dropdown on a select button using focus and enter button. However the enter does not trigger. Here is my code

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  </head>

  <body ng-controller="myCtrl">
    <button id="showButton">Click Me!</button>
    <select id="show">
      <option value=""></option>
      <option value="">One</option>
      <option value="">Two</option>
      <option value="">Three</option>
    </select>
    <input type = "text" id="dean">
    <script type="text/javascript">
      $("#showButton").click(function(){
        $("#show").focus();
        e = $.Event('keyup');
        e.keyCode= 13; // enter
        $('#show').trigger(e);
      });
    </script>
  </body>
</html>
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116

2 Answers2

1

This probably only works in Chrome.

$("#showButton").click(function() {
  var e = new MouseEvent('mousedown',  {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  
  $("#show")[0].dispatchEvent(e);
});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>

<body ng-controller="myCtrl">
  <button id="showButton">Click Me!</button>
  <select id="show">
    <option value=""></option>
    <option value="">One</option>
    <option value="">Two</option>
    <option value="">Three</option>
  </select>
  <input type="text" id="dean">
</body>

</html>
Cornwell
  • 3,304
  • 7
  • 51
  • 84
1

I would checkout something like this:

Trigger a select form element to show its options (open drop down options list) with Javascript

HTML

<input type="button" id="show" value="show" />
<select id="myslect">
    <option>nothing</option>
    <option>something</option>
    <option>anything</option>
</select>

JAVASCRIPT

$("#show").click(function () {
    var element = $("select")[0],
        worked = false;
    if(document.createEvent) { // all browsers
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            worked = element.dispatchEvent(e);
    } else if (element.fireEvent) { // ie
        worked = element.fireEvent("onmousedown");
    }
    if (!worked) { // unknown browser / error
        alert("It didn't worked in your browser.");
    }
});

An other solution would be mimicking the dropdown and toggle the state of that one. Not the best way of doing it but that way you have complete control of the element.

Community
  • 1
  • 1
Wart Claes
  • 223
  • 1
  • 11