Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set "onclick" attribute of dynamic button 1

Status
Not open for further replies.

greedyzebra

Technical User
Sep 5, 2001
140
0
0
US
Hi,

I'm dynamically creating a button with the following code:

var commentButton = document.createElement("input");
commentButton.type = "button";

And I wish to have the button do something when it is clicked (as you would with most buttons). How can I do this?

I've unsuccessfully tried:
commentButton.onclick = "myFunction()";
commentButton.onClick = "myFunction()";
commentButton.onClick = myFunction();

Thanks!
 
here is an example.


<html>
<head>
<script language=&quot;javascript&quot;>
function AddEditControl()
{
var el = document.createElement(&quot;input&quot;)
el.setAttribute(&quot;type&quot;, &quot;button&quot;);
el.setAttribute(&quot;name&quot;, &quot;btnCLick&quot;);
if ((!document.all)&&(document.getElementById)){
el.setAttribute(&quot;onClick&quot;,&quot;test(this)&quot;);
}
//workaround for IE 5.x
if ((document.all)&&(document.getElementById)){
el[&quot;onclick&quot;]=new Function(&quot;test(this)&quot;);
}


el.setAttribute(&quot;value&quot;, &quot;click me&quot;);

document.forms.myForm.appendChild(el);

}

function test(theField)
{

alert(&quot;Clicked &quot; +theField.name);
}
</script>
</head>
<body>
<form name=&quot;myForm&quot;>


</form>


<script language=&quot;javascript&quot;>
AddEditControl()
</script>
</body>
</html>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top