Search code examples
javascripthtmldomdom-eventsdhtml

Using Javascript to change the method/function an HTML element calls


I was wondering if its possible to use Javascript to change the function/method that an HTML element calls.

Example:

<input type="button" id="some_id" name="some_name" value="A Button" onclick="someFunction()" />

I now want to use Javascript to change the method/function called on the onclick event to another function has displayed below.

<input type="button" id="some_id" name="some_name" value="A Button" onclick="anotherFunction()" />

I tried using innerHTML, and when I checked the generated HTML, it actually changed the value of the onclick event in the button, but when I click the button, the method is not called.


Solution

  • You can assign a function object directly to the onclick field of the element. For example,

    var inp = document.getElementById( 'some_id' );
    inp.onclick = anotherFunction;