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

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

Leave a Comment