Passionate Development From Journeyman to Master

Changing javascript event attribute on the fly

This doesn't work in IE, in fact this was one of the problems that responsible for my staying late during the production release mentioned on the previous post.

For that particular project, we have a common user interface (UI) for both adding and editing a record. I use jQuery to change the interface depending on the mode. One of the UI elements that I need to change is the save button's behaviour. Below is the expected behaviour:

  • In add mode, the text is "Add new multi type" and the onclick value is set to something like: addEditMultiType( 'add', 5 ).
  • In edit mode, the text is "Save multi type" and the onclick value is set to something like: addEditMultiType( 'edit', 5 ).

If I haven't really dig jQuery, I would approach this requirement by creating 2 buttons inside 2 divs with display toggled block and hidden depending on the mode. However I was interested in trying this crazy idea, all of the event triggers (onClick, onChange, onBlur etc2)  in HTML element are in fact just attributes right? So I can in fact just create one button and use the awesome jQuery to change the button's text and its onClick depending on the mode.

Below is an example of what I did:

[code=”js”] function changeOnClick( mode ){ $(‘[name=”click me”]’).attr(‘onclick’,’alert(“mode : ‘+mode+’”)’); } [/code]


Worked fine in Firefox, but not in IE7. It took me a long time to figure out this problem. After I figured out what the problem was, I had to go back the tried and tested solution, that is creating 2 buttons with 2 divs, perhaps not as elegant but guaranteed to work all the time. Lesson learned: don't try to be too smart, sometimes simple solution is the best.