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...??
To select multiple items, the user has to hold down the shift or ctrl key, then select with the mouse.
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.
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.
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');
});
});
//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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With