Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use JS to open an HTML select to show its option list? [duplicate]

People also ask

How do you show a selected list in HTML?

Select lists are created using a combination of the HTML <select> and <option> tags. Select lists can be nested inside a <form> element or they can stand alone. They can also be associated with a form via the form attribute of the <select> tag.


Unfortunately there's a simple answer to this question, and it's "No"


I had this problem...and found a workable solution.

I didn't want the select box to show until the user clicked on some plain HTML. So I overlayed the select element with opacity=.01. Upon clicking, I changed it back to opacity=100. This allowed me to hide the select, and when the user clicked the text the select appeared with the options showing.


This works on Google Chrome

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);
};

I use this... but it requires the user to click on the select box...

Here are the 2 javascript functions

function expand(obj)
{
    obj.size = 5;
}
function unexpand(obj)
{
    obj.size = 1;
}

then i create the select box

<select id="test" multiple="multiple" name="foo" onFocus="expand(this)" onBlur="unexpand(this)">
<option >option1</option>
<option >option2</option>
<option >option3</option>
<option >option4</option>
<option >option5</option>
</select> 

I know this code is a little late, but i hope it helps someone who had the same problem as me.

ps/fyi i have not tested the code above (i create my select box dynamically), and the code i did write was only tested in FireFox.


After trying to solve this issue for some time, I managed to come with a working solution that is also valid:

var event = new MouseEvent('mousedown');
element.dispatchEvent(event);

I've tried to implement this in Jquery as well, using trigger and mousedown or only mousedown but with no success.


This is very late, but I thought it could be useful to someone should they reference this question. I beleive the below JS will do what is asked.

<script>     
         $(document).ready(function()
           {
          document.getElementById('select').size=3;
           });
    </script>