28

How can a dropdown list can be opened with a trigger?

Here is the code which doesn't work:

$('select').trigger('click');

Just for note - mousedown and mouseup also doesn't work.

5

5 Answers 5

13
$('select').children('option').each(function() {
    if ($(this).is(':selected'))
    { $(this).trigger('change');  }
});
1
  • 2
    This might fire other attached events which you probably dont want.
    – Jonathan
    Commented Aug 6, 2014 at 13:49
9

What you are trying to achieve is impossible. Even if you trigger a click the drop down list won't open like if the user clicked on it. If you want to change the currently selected value with a new one you could use the val function. I guess the only solution is to simulate the whole UI look and feel of a select element using divs.

2
  • 1
    Thanks for response. I don't want to change value, just want to open list... It seems that there isn't propertly solution for this...
    – sasa
    Commented May 24, 2010 at 8:37
  • it's explicitly denied by spec, @sasa :(
    – Hashbrown
    Commented Feb 5 at 1:54
8

Took me a while but found a solution:

(Chrome & Safari ONLY)

function open(elem) {
    if (document.createEvent) {
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem[0].dispatchEvent(e);
    } else if (element.fireEvent) {
        elem[0].fireEvent("onmousedown");
    }
}

http://jsfiddle.net/oscarj24/GR9jU/

3
  • 5
    Close. This works in Chrome & Safari, but doesn't work in Firefox or IE. Commented Aug 15, 2014 at 22:14
  • 1
    On chrome Version 75.0.3770.27 it's not working. But in Safari Version 12.1 (14607.1.40.1.4) It's working fine.
    – Bijay Rai
    Commented May 23, 2019 at 9:24
  • yeah @BijayRai it was removed
    – Hashbrown
    Commented Feb 5 at 1:54
5

There is no proper way to click on a dropdown programmatically.

You can either select an option via:

$('#sourceOptions>option:eq(0)').prop('selected', 'selected');

If you want to simulate a user click: you have to do it as @Renso says it:

$('#sourceOptions>option:eq(0)').prop('selected', 'selected').trigger('change');
0
0

Instead of trigger give it a size. This simply opens the select (tested in Chrome):

/////// $('select').trigger('click'); $('select')[0].size = 10;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.