Dynamically Change the onClick, onChange (or other) Value of an Element

If you are implementing AJAX, you will likely run into the need to change the functionality of a button dynamically. There is not a whole lot out there on how to quickly accomplish this so here is a simple explanation.

Typically, you have an element such as an “input”, “a” or “select (options)” that has an attribute of “onClick”, “onMouseOver” or “onChange” with a value of some function that will execute upon the event represented by the attribute.

UPDATE: This has been changed to accommodate ie. The following way will work in both Firefox and Internet Explorer:

button_element.onclick = function() {doSomething();};

Thanks! to this post. (note: the answer is at the bottom of the post after some discussion.) Thanks for sharing

To assign a new value to the attribute, you need to identify the element you want to change like this:

elem =  document.getElementById(“myElementId”)

Then simply assign the new value to the attribute like this:

elem.attributes[“onclick”].value = “myUpdatedFunction(‘My parameter’)” ;

Now, if someone clicks on the element, the new updated version of myUpdatedFunction() will be called. Notice that you can even pass a parameter to the function this way. Just be sure to nest your quotes properly.

This method will also work for other attribute types such as onMouseOver, onChange an so on.

I hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *