Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically expand html select element in javascript

I have a (hidden) html select object in my menu attached to a menu button link, so that clicking the link shows the list so you can pick from it.

When you click the button, it calls some javascript to show the <select>. Clicking away from the <select> hides the list. What I really want is to make the <select> appear fully expanded, as if you had clicked on the "down" arrow, but I can't get this working. I've tried lots of different approaches, but can't make any headway. What I'm doing currently is this:

<li>
    <a href="javascript:showlist();"><img src="/images/icons/add.png"/>Add favourite</a>
    <select id="list" style="display:none; onblur="javascript:cancellist()">
    </select>
</li>

// in code
function showlist() {
    //using prototype not jQuery
    $('list').show();  // shows the select list
    $('list').focus(); // sets focus so that when you click away it calles onblur()
}
  • I've tried calling $('list').click().
  • I've tried setting onfocus="this.click()" But in both cases I'm getting

Uncaught TypeError: Object # has no method 'click'

which is peculiar as link text says that it supports the standard functions.

I've tried setting the .size = .length which works, but doesn't have the same appearance (as when you click to open the element, it floats over the rest of the page.)

Does anyone have any suggestions?

like image 811
xan Avatar asked May 27 '10 18:05

xan


People also ask

How do you populate the options of a select element in JavaScript?

To populate select list with jQuery, use for loop along with append() and append the options to the already created select.


1 Answers

I've come across the same problem, wanted to implement keyboard navigation in my app, but select elements were not expanded, so people using the keyboard were going to lose functionality. I've created ExpandSelect() function which emulates mouse clicks on select elements, it does so by creating another <select> with multiple options visible at once by setting the size attribute, the code is hosted on Google Code website, ExpandSelect.js is only 4 KB, see screenshots and download it here:

http://code.google.com/p/expandselect/

Screenshots

There is a little difference in GUI when emulating click, but it does not really matter, see it for yourself:

When mouse clicking:

MouseClicking
(source: googlecode.com)

When emulating click:

EmulatingClicking
(source: googlecode.com)

More screenshots on project's website, link above.

like image 168
Czarek Tomczak Avatar answered Sep 25 '22 12:09

Czarek Tomczak