1

What I am trying to achieve is I want to click on a div, that will make a select box drop down. So something like this:

$('#test div').click(function(){
    $('#test select').dropDown();
});

Is there such an action that does this? Or even some kind of work around?

Source
  • 1,026
  • 4
  • 11
  • 23
  • Possible duplicate of [Click trigger on select box doesn't work in jQuery](http://stackoverflow.com/questions/2895608/click-trigger-on-select-box-doesnt-work-in-jquery) – Dekel Sep 14 '16 at 01:20

1 Answers1

2

(function($) {
    "use strict";
    $.fn.openSelect = function()
    {
        return this.each(function(idx,domEl) {
            if (document.createEvent) {
                var event = document.createEvent("MouseEvents");
                event.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                domEl.dispatchEvent(event);
            } else if (element.fireEvent) {
                domEl.fireEvent("onmousedown");
            }
        });
    }
}(jQuery));

$('#test div').click(function(){
  $('#test select').openSelect();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <div>
    Click
  </div>
  <br /><br />
  <select>
    <option>123</option>
    <option>456</option>
    <option>789</option>
  </select>
</div>

You could register the following jQuery function:

(function($) {
    "use strict";
    $.fn.openSelect = function()
    {
        return this.each(function(idx,domEl) {
            if (document.createEvent) {
                var event = document.createEvent("MouseEvents");
                event.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                domEl.dispatchEvent(event);
            } else if (element.fireEvent) {
                domEl.fireEvent("onmousedown");
            }
        });
    }
}(jQuery));

And simply call it by: $('#test select').openSelect();

Try on JsFiddle: https://jsfiddle.net/Zay_DEV/ptkxhky1/

Geeky Ninja
  • 6,002
  • 8
  • 41
  • 54
Zay Lau
  • 1,856
  • 1
  • 10
  • 17