Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open the select input using jquery

So I can see the options of the select element but I need to click on it. What if I want to use a function? When something happens this select element should be selected, means the list is open and I can see the options. I don't want the user to click on the select element, I want something else to open it.

What I've tried

$("select").select();
$("select").click();
$("select").focus();

There is a select element, usually if you want it to open (the drop down list), you click on it. What I want is to open it if I click on a DIV or anything else. I want this drop down list to to open, without having the user clicking on the select element.

like image 787
Ali Bassam Avatar asked May 04 '12 17:05

Ali Bassam


1 Answers

This should work:

var element = $("select")[0], worked = false;
if (document.createEvent) { // all browsers
    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);
} else if (element.fireEvent) { // ie
    worked = element.fireEvent("onmousedown");
}
if (!worked) { // unknown browser / error
    alert("It didn't worked in your browser.");
}

Example

like image 171
noob Avatar answered Oct 15 '22 10:10

noob