Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand select dropdown

Tags:

jquery

I am trying to expand a select dropdown upon clicking on a link.

<button type="button" id="btn">Click Me!</button> 
<select id='sel' name='sel'>
    <option>item 1</option>
    <option>item 2</option>
    <option>item 3</option>
    <option>item 4</option>
</select>

And the Javescript is as follows.

$(document).ready(function() {
    $("#btn").click(function() {
       $("#sel").trigger('click');
    });
});

Any Ideas...??

like image 370
user2289967 Avatar asked Apr 17 '13 09:04

user2289967


People also ask

How do I select multiple options from a drop-down list in HTML?

To select multiple items, the user has to hold down the shift or ctrl key, then select with the mouse.

How more than one option can be selected in drop-down?

To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.

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

You can use your keyboard to open select fields already. Typically, (it depends on your browser) you tab to the field and then press the down or up arrow to open the select and scroll through the options.


2 Answers

You cannot mimic native browser event using .trigger. Looking at this link to the jQuery tutorial it seems you need .simulate method from jquery.simulate.js. Moreover the open event of the dropdown box is given by mousedown not click.

Update: So the code become:

$(document).ready(function() {
    $("#btn").click(function() {
       $("#sel").simulate('mousedown');
    });
});
like image 81
Alepac Avatar answered Oct 11 '22 00:10

Alepac


//https://stackoverflow.com/a/10844589/7926961
  function openDropdown(elementId) {
        function down() {
            var pos = $(this).offset(); // remember position
            var len = $(this).find("option").length;
                if(len > 20) {
                    len = 20;
                }

            $(this).css("position", "absolute");
            $(this).css("zIndex", 9999);
            $(this).offset(pos);   // reset position
            $(this).attr("size", len); // open dropdown
            $(this).unbind("focus", down);
            $(this).focus();
        }
        function up() {
            $(this).css("position", "static");
            $(this).attr("size", "1");  // close dropdown
            $(this).unbind("change", up);
            $(this).focus();
        }
        $("#" + elementId).focus(down).blur(up).focus();
    }

DEMO:

http://jsfiddle.net/XE73h/444/

like image 31
Jefferson Reis Avatar answered Oct 10 '22 23:10

Jefferson Reis