Problem with Javascript object and dynamically created buttons

M

mikevanoo

Hi,

Can anyone work out why the following doesn't work. For some reason,
when you dynamically add a button to the document from a Javascript
object it can't then reference the properties of the object like a
"normal" button. Any ideas?

Thanks in advance,

Mike.

===================================================================
<html>
<head>
<script type="text/javascript">

var obj;

function TestObject () {
this.ID = "testObject1";
this.Init = TestObject_Init;
this.Test = TestObject_Test;
}
function TestObject_Init() {
this.Button = document.createElement("INPUT");
this.Button.type = "button";
this.Button.value = "Dynamically Added Button - this should display
\"testObject1\" but doesn't!";
this.Button.onclick = this.Test;
document.body.appendChild(this.Button);
}
function TestObject_Test() {
alert(this.ID);
}

function Go() {
obj = new TestObject();
obj.Init();
}

</script>
</head>
<body onload="Go()">
<input type="button" value="Static Button - This works as it should."
onclick="obj.Test();" />
</body>
</html>
===================================================================
 
M

marss

function TestObject_Test() {
alert(this.ID);
}

It does not work because "this" in that case is not obj (instance of
"TestObject"), but it is obj.Button.
If purpose of this script is showing popup message "testObject1", you
have to correct script a little.

var obj;

function TestObject () {
this.ID = "testObject1";
this.Init = TestObject_Init;
this.Test = TestObject_Test;
}
function TestObject_Init() {
this.Button = document.createElement("INPUT");
this.Button.type = "button";
this.Button.value = "Dynamically Added Button - this should
display \"testObject1\" but doesn't!";
this.Button.onclick = this.Test;
this.Button.parent = this; //first change
document.body.appendChild(this.Button);
}
function TestObject_Test() {
alert(this.parent.ID); //second change
}

function Go() {
obj = new TestObject();
obj.Init();
}
 

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

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top