How to AttachEvent for dynamically added controls?

J

jiayanxiang

Hi:

I used the following code to dynamically add a control and I tried to
use attachevent to add a onClick event to the control. It doesn't seem
to do anything. Any idea what might be wrong?

Thanks.

<HTML>
<HEAD>

<script language="javascript">
function AddOneCtl() {
var ni = document.getElementById('myDiv');
var newctl2 = document.createElement('button');
newctl2.setAttribute('id','Test1');
newctl2.setAttribute('value','Click Me');
ni.appendChild(newctl2)
document.getElementById('Test1').attachEvent('onClick',clickevt1);
}

function clickevt1() {
alert("Clicked");
}

</script>

</HEAD>

<BODY>
<FORM name="AddControl">
<INPUT TYPE="button" VALUE="Click here to add a control"
onClick="AddOneCtl()">
</FORM>

<div id="myDiv"> </div>

</BODY>
</HTML>
 
M

Martin Honnen

jiayanxiang wrote:

document.getElementById('Test1').attachEvent('onClick',clickevt1);

It should be 'onclick', not 'onClick'. However note that attachEvent is
part of the IE 5 DOM, some other browsers like Opera implement that too,
but Mozilla needs the W3C DOM specific addEventListener.

Simply setting
elementNode.onclick = clickevt1;
should suffice however.

Additionally the HTML button element is not a good choice on the web, it
has different default values for the type attribute (e.g. 'submit' for
Mozilla, 'button' for IE) and IE insists on submitting the content
(innerText) of the button element if it is a submit button.
 
J

jiayanxiang

Thanks, it worked fine now.

The page I am working on is internal and for IE only. (We can't even
run firefox here:( ) so it simplifies things a little.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top