Reputation: 7364
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>
Upvotes: 1
Views: 3392
Reputation: 233
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.
Upvotes: 1
Reputation: 3410
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>
Upvotes: 1