Source
Source

Reputation: 1021

How to make a select box drop down, by clicking somewhere else than the select box with jquery

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?

Upvotes: 1

Views: 37

Answers (1)

Zay Lau
Zay Lau

Reputation: 1864

(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/

Upvotes: 2

Related Questions