Link to home
Start Free TrialLog in
Avatar of paulmedina
paulmedina

asked on

Get text string of event handler in button.

Hi,

I have a button whose onclick event calls a javascript function:

e.g.
<input type="button" id="aButton" onClick="someFunction( 'textvalue', this, null )">

How can I get the text string of that function call?

I've tried:

var thecode ;
var somebutton = document.getElementById('aButton');
if( document.all )
   thecode = somebutton.getAttribute('onclick') ; //in I.E.
else
   thecode = somebutton.onclick; //mozilla

However, this just causes the button's onclick event to get fired instead of returning the text.

Any ideas?

Thanks in advance!

Paul
Avatar of paulmedina
paulmedina

ASKER

Never mind I figured it out.

I used:

if( document.all )
   thecode = somebutton.getAttribute('onclick').toString() ; //in I.E.
else
   thecode = somebutton.onclick.toString(); //mozilla


Thanks everyone.
Will this work?

<html>
<head>
<script type="text/javascript">
function someFunction(str, btnObj, something)
{
  alert(str);
}

function getFuncStr(id)
{
  var someButton = document.getElementById(id);
  var strFunc = someButton.onclick.toString();

  // both IE & Firefox wrap it in some other function
  // we need to strip it out
  strFunc = strFunc.replace(/^function [^{]+\s?{/, "").replace(/}$/,"");

  alert(strFunc);
}
</script>
</head>

<body>
<form>
  <input type="button" id="aButton" value="calls someFunction" onclick="someFunction('textvalue',this, null);">
  <input type="button" value="get aButton's onclick" onclick="getFuncStr('aButton');">
</form>
</body>
</html>

The only thing I think you did wrong was to not use the toString() for the onclick.  In this case, the important part is what's in the getFuncStr() function.  I passed in the id of the button you want, but you can make it work just as easily if you can identify the button without passing in the ID.  Hope that helps.
Oops, looks like I was a couple of minutes late on this one.  You can ask in Community Support to get this closed out for you.
Avatar of Zvonko
How about this:


<body>
<form>
<input type="button" id="aButton" onClick="someFunction( 'textvalue', this, null )">

<input type="button" value="getString" onClick="alert((this.form.aButton.onclick+'').match(/'([^']+)'/)[1])" >
</form>
</body>



ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial