Here is the markup
<select id="person_prefix" name="prefix">
<option value=""></option>
<option value="Dr" selected="selected">Dr</option>
<option value="Mr">Mr</option>
<option value="Ms">Ms</option>
<option value="Mrs">Mrs</option>
</select>
and I want to trigger a javascript event so that the option list drops down. Using jquery I've tried the following:
$("#person_prefix").click();
$("#person_prefix").mousedown();
$("#person_prefix").change();
but nothing seems to work. Which event is this and how can be triggered?
Thanks
Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.
You can use your keyboard to open select fields already. Typically, (it depends on your browser) you tab to the field and then press the down or up arrow to open the select and scroll through the options.
The trick is that ALT-Down Arrow is a shortcut key to open a select drop down.
I was once searching how to do the same thing and didn't find any working solution but then a guy in our javascript group came with a clever work around. Here is the code.
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) { // chrome and safari
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);
}
if(!worked) { // unknown browser / error
alert("It didn't worked in your browser.");
}
});
I'm not sure how to link to the group post so you can see the whole thread. Anyway credits to CJ Madolara. Good Job!
Update: Only works on Chrome and Safari
You can't do this cross-browser programmatically. You can replace the dropdown with an entirely custom solution not actually displaying a <select>
element...but you can't programmatically show it, especially in IE.
The closest you can do is move the user to the element via .focus()
:
$("#person_prefix").focus();
This with some CSS styling for when it's focused (:focus
) is usually a pretty good way to draw attention to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With