Sunday, December 28, 2008

Weird behaviour of "onchange" event of Listbox in FireFox

The HTML listbox has an "onchange" event which is fired whenever the item selected in the listbox has been changed. The contents of the listbox can be changed either by clicking the corresponding item from the listbox or by using the up and down arrow keys or pressing the beginning alphabet of any of the items when the listbox has focus. Ideally, even when changing the selected item by using the keyboard, the onchange event should be fired. In fact, the event is fired in all major browsers except Firefox. With Firefox, the onchange event is called only when the listbox loses focus.

Suppose you have a form whose contents you would like to change based on the value selected in the listbox. For example, have different fields on the form based on whether the user is interested in Sports, Music, Dance etc. You can do this by capturing the item selected by the user in the onchange event and making the necessary changes by manipulating the DOM. However, you would have a problem with users using FireFox. To be able to capture the value every time the user makes a new selection, we need to add some javascript for the "onkeyup" event. The code needed is,

<select id="items" onchange='itemSelected();' onkeyup="this.blur();this.focus();">
</select>

All that needs to be done is to momentarily remove focus from the listbox so that the onchange event is called and then, set the focus again. Setting the focus again on the listbox is needed because, if we don't do that, the user will have the set the focus explicitly on the listbox every time he changes it's value with the keyboard - he wouldn't appreciate this if he wants to select a value which is 4-5 values further in the list from where he's currently at.

I spent nearly 2 hours trying to figure out why the onchange event wasn't getting called in FireFox. Hope this post will go some way in helping you reduce the debugging time in case you happen to come across a similar situation.

5 comments:

  1. hey..for you as well as others, in case u encounter such issues with firefox, lookup the bugzilla to find out if this is an issue with firefox or you messed up somewhere.. for this particular issue: https://bugzilla.mozilla.org/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=Firefox&content=onchange

    ReplyDelete
  2. Brilliant solution - helped me very much. Thanks.

    ReplyDelete
  3. Thanks alot! Very kind of you!

    ReplyDelete
  4. Cool article you got here. It would be great to read more about this topic.
    By the way look at the design I've made myself Female escorts

    ReplyDelete
  5. It was very interesting for me to read this blog. Thanks the author for it. I like such themes and everything connected to this matter. I would like to read more on that blog soon.

    Best regards

    ReplyDelete