0

Imagine you have a button like this:

<input name="myButton" type="button" value="button" onclick="return test();" >

where the test functions is as follows:

function test(){
  // do something
  return true; // based on some logic return boolean
}

Now let's say,I don't know what is set for the onclick event, and at runtime I need to read the function or any code set to onclick and run it. Here is an example:

var btn = getElementById('myButton');
var btnOnClickFunc = btn.onclick;
if (btnOnClickFunc) {
    // do something
}

I know this doesn't work, and that's actually my question. How can I read the button's onclick event in this example at runtime?

An example of this case is when the onclick is attached to the button later using jQuery.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Amin Emami
  • 497
  • 2
  • 5
  • 12

1 Answers1

4

If you need to do this you might want to eventually refactor your code so that you no longer need to do this. In the meantime you can use this hack:

$('#myButton').attr('onclick')();

The attribute 'onclick' actually returns a function, so calling it with () actually executes that function.

If you'd rather not use jQuery, you don't have to. The following works without it:

document.getElementById('myButton').onclick();

Also, for either of these two, you can break it up into two lines:

var clickFunc = $('#myButton').attr('onclick');
...
clickFunc();
Danny Roberts
  • 3,442
  • 23
  • 28
  • Thanks for the answer! That worked. This code is part of a framework which connects various parts together. The function and the onclick event will be written by the developer and the framework do more stuff behind the scene. That's the reason I need to read developer's code. It doesn't need to be refactored for the reason I just mentioned. – Amin Emami Jan 13 '10 at 00:30