Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keypress/keyup/etc events not fired when select box is expanded

Check out my code sample here: http://pastebin.com/D1ZctG11

The gist is: If you have a select box expanded (either via the keyboard or mouse), jquery's key events do not seem to fire - at least not in Mac Chrome.

Are there any workarounds?

My end goal is to select what the user has typed while the select box is expanded when using the optgroup element.

edit:

jsfiddle link: http://jsfiddle.net/XacfX/

Thanks
Mustafa

like image 228
Mustafakidd Avatar asked Dec 27 '11 20:12

Mustafakidd


3 Answers

I think you have to use jQuery's change():

http://jsfiddle.net/vvBqE/11/

Unless I misunderstood you, you can see which option the user has selected this way. You can also use the key events in my example but the callback function won't be triggered if the user selects an option by using mouse only.

like image 146
Bay Avatar answered Sep 28 '22 05:09

Bay


Buggy indeed, I can't find an explanation anywhere but it seems related to the fact that the browser will render the dropdown popup even outside the browser window (try to make your browser really small and open your dropdown, it leaves the boundaries), making it not a typical document element.

One work around is to add a size on the dropdown

<select name="sel_id" id="sel_id" size=5>
  <option value="0">Choose a new fixer...</option>
    <optgroup label="Group A">
    <option value="6366">Test User useruser</option>
  </optgroup>
  <optgroup label="Group B">
    <option value="5831">First Guy</option>
    <option value="1123">Second Guy</option>
    <option value="7232">Second Second Guy</option>
  </optgroup>
</select>

$(document).keypress(function(e){
    console.log(String.fromCharCode(e.keyCode));
});

I am sure some DOM experts around can give some light on this one.

like image 44
Francisco Aquino Avatar answered Sep 28 '22 06:09

Francisco Aquino


As this indeed seems to be bugged you might want to try something like this as a workaround:

http://www.devirtuoso.com/2009/08/styling-drop-down-boxes-with-jquery/

That would render the select box as a styled list in the end. Some tweaking to enable optgroups with that solution and voilá you got a dropdown box that is rendered inline with the page and therefore doesn't block key events.

On the upside you also get to style the dropdown any way you want :)

like image 38
bardiir Avatar answered Sep 28 '22 06:09

bardiir