Is there a way to open a select box using Javascript (and jQuery)?
Try this:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
and this to close:
//close dropdown
myDropDown.attr('size',0);
Try this:
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
Then call the function:
dropDown('elementId');
The mousedown event is raise before the click event :
The blur and change event are needed to close the dropdown if the user clicked outside the dropdown.
Here the complete solution with Brendan's code :
(function ($) {
var open = {}
$.fn.IELongDropDown = function (cln) {
if (jQuery.browser.msie) { //only IE has problems with long select boxes
var el = this;
var id = el.attr('id');
var margin = 2; //Need to set a margin however the arrow is cut
var previousWidth = el.width() + margin;
var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:" + previousWidth + "px'></div>";
el.wrap(divWrapper);
var newWidth = el.width("auto").width();
el.width(previousWidth);
if (newWidth > previousWidth) {
el.mousedown(function () {
if (!open[id]) {
el.width("auto");
el.focus();
}
});
el.click(function () {
if (!open[id])
open[id] = true;
else {
open[id] = false;
return el.width(previousWidth);
}
});
el.blur(function () {
open[id] = false;
return el.width(previousWidth);
});
el.change(function () {
open[id] = false;
return el.width(previousWidth);
});
}
}
return this;
};
})(jQuery);
Call the function :
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#mydropdownlist').IELongDropDown();
});
</script>
you can not open the select list but you can do it by changing the size of theselect list on click or any other event you want
$("#drpdwn").mousedown(bodyevent);
function bodyevent()
{
console.log("size changed");
$(this).attr('size',3);
}
$("#drpdwn").focus(function()
{
//alert("txt clicked from ");
var $el = $("#drpdwn");
var offset = $el.offset();
var event = jQuery.Event( "mousedown", {
which: 1,
pageX: offset.left,
pageY: offset.top
});
$el.trigger(event);
});
As an alternative you can use the select2 plugin and do the following:
$(element_select).focus();
$(element_select).select2('open').trigger('open');
It worked perfectly for me in Firefox version 79.0
I know this is pretty old and answered, but this worked for me in Safari and iOS UIWebView - I have it hidden, but want it to show and open when a different button is clicked.
$('#select-id').show().focus().click();