views:

57

answers:

2

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.

Thanks in advance.

+3  A: 

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;
friedo
tried it but n not working.
IndexController
Define "not working." This is the standard way to assign event handlers in raw Javascript.
friedo
when assigning anotherFunction to the onclick event, it executes the function immediately, which is not what i want. i want the function be executed onclick of the element
IndexController
No, it won't execute the function - be sure to copy friedo's code *exactly* as he has provided it -> that is, there is no `()` after `anotherFunction` which means you are assigning a function reference, not executing it. +1 to this one for *not* referring to a library/framework, because I think he needs to learn the basics first.
Graza
Thx Graza, u guys are right, but this is one more thing. The new assigned function accepts two parameters. How do i get to pass the function parameters?
IndexController
Got it, what i did was var afunc = function() //create a anonymous function { newfunction(args1, args2) //call the new function with the required parameters } element.onclick = afunc // I then assigned the reference of the anonymous functions to the onclick event of the element.Thank u so much guys for putting me in the right path. I really appreciate.
IndexController
@Index, you can save yourself a little typing by just doing `element.onclick = function() { newfunction( arg1, arg2 ); }`
friedo
+1  A: 

Using jQuery you could do:

$('#some_id').unbind('click');
$('#some_id').click(function () { 
    anotherFunction();
});
SoloBold
Ah, you are totally right. You have to unbind it first. Thanks, I hadn't realized that :)
SoloBold
Comment clashes - I deleted my original comment after you edited. +1 for jQuery *but* I also don't think this developer should be using it just yet - would probably be better off learning the basics first
Graza