开发者

Adding options to select element at the point it's about to open in JavaScript

I have a system with a fast-changing set of items that may appear as options in select boxes. I could update the options themselves directly each time the data changes, but I'd rather simply fill in the options at the point where the user is about to see them. E.g. when it's about to open. Is there an event for this?

I suppose I could use the 'click' or 'mousedown' event, but what about navigating via the keyboard? There may be other cases too (perhaps)

BTW, I know how to add options to 开发者_JS百科a select, the 'opening' event is really what I'm after.

Thanks, Ben


You've got two choices: click() and focus() there are no others.


Use focus() and not click() because the click event does not give enough time to populate the drop down with new values which causes quirky behavior. Also the click event will only capture mouse clicks, with the focus() you get both mouse and keyboard focus events and also it gives ample time for the drop down to get populated with new data. Here is a fiddle with some simple experiments, try each function one at a time to see the difference.


If you're doing something like this, a select drop down probably isnt going to be the UI element of choice.

I would recommend changing to a jQuery UI Autocomplete widget; then you can simply serve items based on the query the user entered.

In addition, you can attach to the keyup event (or the focus event), and show a set of items at that point (as if the 'drop down' was clicked on) http://jqueryui.com/demos/autocomplete/#maxheight

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜