473,594 Members | 2,651 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically adding an onClick event.

Daz
Hello everyone. I am sure the answer to my question is simple, but I
can't seem to dynamically add an onClick event to my script.

I have a table which is generated dynamically, I am just struggling
getting an onClick event to show in the HTML source.

Any help would be appreciated. Here is a block of my current code which
doesn't work.

var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var b = document.create Element('b');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";
table.appendChi ld(tr1);
tr1.appendChild (td1);

td1.appendChild (b);
b.appendChild(t itleSpan);
titleSpan.inner HTML = menuTitle;
titleSpan.onCli ck = "this.toggle()" ;

I am assuming that I am missing something with the syntax?

All the best.

Daz.

Nov 11 '06 #1
11 11186
ASM
Daz a écrit :
Hello everyone. I am sure the answer to my question is simple, but I
can't seem to dynamically add an onClick event to my script.

I have a table which is generated dynamically, I am just struggling
getting an onClick event to show in the HTML source.

Any help would be appreciated. Here is a block of my current code which
doesn't work.
var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";

titleSpan.style .fontWeight = "bold";
titleSpan.onCli ck = function() {this.toggle(); };
titleSpan.inner HTML = menuTitle;

td1.appendChild (titleSpan);
tr1.appendChild (td1);
tbody.appendChi ld(tr1);

use tbody instead of table
..
Nov 11 '06 #2
Daz

ASM wrote:
Daz a écrit :
Hello everyone. I am sure the answer to my question is simple, but I
can't seem to dynamically add an onClick event to my script.

I have a table which is generated dynamically, I am just struggling
getting an onClick event to show in the HTML source.

Any help would be appreciated. Here is a block of my current code which
doesn't work.

var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";

titleSpan.style .fontWeight = "bold";
titleSpan.onCli ck = function() {this.toggle(); };
titleSpan.inner HTML = menuTitle;

td1.appendChild (titleSpan);
tr1.appendChild (td1);
tbody.appendChi ld(tr1);

use tbody instead of table
.
Thanks ASM. my table variable is actually a reference to tbody. You're
right, though. I should have named it tbody and not table.

I still can't get it to work. For some reason, the toggle function is
not working at all. I have tried adding the function to the onClick
event directly, and it still doesn't work... I don't even get an
error/warning in my JavaScript Console...

I know it's something I am doing wrong, I just can't figure out what.

Here is my code. It looks messy because I am trying to figure out how
things work...

//********** CODE START **********

var table = document.getEle mentById('ctg_t able');
var tableWidth = 80;

function initPage()
{
table.parentNod e.style.width = tableWidth + "%";
displayInputDia log();
var row1 = new menuItem("test" );
}

function displayInputDia log()
{
var tr = document.create Element('tr');
tr.setAttribute ("id", "rInputDialog") ;
tr.style.height = "20%";
var td = document.create Element('td');
textarea = document.create Element('textar ea');
textarea.setAtt ribute("name", "inputDialo g");
textarea.setAtt ribute("id", "inputDialo g");
textarea.style. width = "100%";
textarea.style. height = "100%";
textarea.style. borderStyle = "ridge";
table.appendChi ld(tr);
tr.appendChild( td);
td.appendChild( textarea);
}

function menuItem (menuTitle)
{
var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var b = document.create Element('b');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";
table.appendChi ld(tr1);
tr1.appendChild (td1);
td1.appendChild (b);
b.appendChild(t itleSpan);
titleSpan.inner HTML = menuTitle;
var tr2 = document.create Element('tr');
var td2 = document.create Element('td');
table.appendChi ld(tr2);
tr2.appendChild (td2);
tr2.style.borde rStyle = 'ridge';
tr2.style.borde rColor = "green";
td2.innerHTML = 'blah';
titleSpan.onCli ck = function()
{
var textarea = document.getEle mentById('input Dialog');
textarea.value = "blah"
}
}

initPage();

//************ CODE END ************

Many thanks for your input.

If you can offer any more constructive criticism, it would be received
gracefully as I would rather do this right, than go about it the wrong
way.

Daz.

Nov 11 '06 #3
ASM
Daz a écrit :
Thanks ASM. my table variable is actually a reference to tbody. You're
right, though. I should have named it tbody and not table.

I still can't get it to work. For some reason, the toggle function is
not working at all. I have tried adding the function to the onClick
event directly, and it still doesn't work... I don't even get an
error/warning in my JavaScript Console...

I know it's something I am doing wrong, I just can't figure out what.

Here is my code. It looks messy because I am trying to figure out how
things work...

//********** CODE START **********

var table = document.getEle mentById('ctg_t able');
var tableWidth = 80;

function initPage()
{
table.parentNod e.style.width = tableWidth + "%";
displayInputDia log();
var row1 = new menuItem("test" );
}

function displayInputDia log()
{
var tr = document.create Element('tr');
tr.setAttribute ("id", "rInputDialog") ;
tr.style.height = "20%";
var td = document.create Element('td');
textarea = document.create Element('textar ea');
IE would prefer :
textarea.name = "inputDialo g";
textarea.id = "inputDialo g";
textarea.setAtt ribute("name", "inputDialo g");
textarea.setAtt ribute("id", "inputDialo g");
textarea.style. width = "100%";
textarea.style. height = "100%";
textarea.style. borderStyle = "ridge";
table.appendChi ld(tr);
tr.appendChild( td);
td.appendChild( textarea);
why do you append something to your td not more there ?

td.appendChild( textarea); // from inside
tr.appendChild( td); // to outside
table.appendChi ld(tr); // boxes
}

function menuItem (menuTitle)
{
var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var b = document.create Element('b');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";
table.appendChi ld(tr1);
tr1.appendChild (td1);
td1.appendChild (b);
b.appendChild(t itleSpan);
titleSpan.inner HTML = menuTitle;
var tr2 = document.create Element('tr');
var td2 = document.create Element('td');
Same as I previously said : better to append in right order

p or span -td -tr -tbody -table -body
table.appendChi ld(tr2);
tr2.appendChild (td2);
tr2.style.borde rStyle = 'ridge';
tr2.style.borde rColor = "green";
td2.innerHTML = 'blah';
titleSpan.onCli ck = function()
perhaps :
titleSpan.oncli ck = function()
{
alert('seen');
var textarea = document.getEle mentById('input Dialog');
textarea.value = "blah"
}
}

initPage();

//************ CODE END ************

Many thanks for your input.
a question : is this table in a form ?
Nov 11 '06 #4
Daz

ASM wrote:
IE would prefer :
textarea.name = "inputDialo g";
textarea.id = "inputDialo g";
Ok, I have changed this in my code. Thanks :)

I'd just like to point out that I don't have access to Internet
Explorer, so I am using Firefox. As far as I know it shouldn't be a big
issue, but I know some things are different between the way that
Internet Explorer and Firefox process JavaScript, or rather the syntax
and attributes which should be used.
why do you append something to your td not more there ?
Sorry, I don't understand what you mean. Are you suggesting I use
innerHTML instead of appending textarea?
td.appendChild( textarea); // from inside
tr.appendChild( td); // to outside
table.appendChi ld(tr); // boxes
Ok, I have changed my code to reflect this. It makes more sense doing
it the way you suggested, although I was simply going by the examples
by Mark Kahn at
http://www.htmlgoodies.com/primers/j...le.php/3594621
Same as I previously said : better to append in right order
Agreed, and already done.
p or span -td -tr -tbody -table -body
There are no body tags in my HTML. Would this make any difference as
everything goes inside my <tbody>? Everything is displaying correctly,
it's just this single function that is refusing to fire.
perhaps :
titleSpan.oncli ck = function()
I have tried just doing:
titleSpan.onCli ck = function() { alert('blah'); }
....and it still won't fire...
a question : is this table in a form ?
No, I'm not, and I don't plan to either. :)

Here is the code modified following your suggestions. I have included
the HTML also, in case I have made a stupid mistake.

//***** CODE START *****
/*************
* HTML code *
************/
<head>
<title>Colour Text Generator</title>
</head>
<table style="width: 100%;">
<tbody id="ctg_table" >
</tbody>
</table>
<script language="javas cript" type="text/javascript" src="text_gener ator.js"></script>
<noscript>
You must enabled JavaScript in order to use this page.<br /><br />
If you do not have a JavaScript enabled browser, please download Firefox
for free from <a href="http://www.getfirefox. com">www.getfir efox.com</a>.
</noscript>
//*************** ***
* JavaScript code *
*************** ***/
var tbody = document.getEle mentById('ctg_t able');
var tableWidth = 80;
var row1 = null;
function initPage()
{
tbody.parentNod e.style.width = tableWidth + "%";
displayInputDia log();
row1 = new menuItem("test" );
}
function displayInputDia log()
{
var tr = document.create Element('tr');
tr.setAttribute ("id", "rInputDialog") ;
tr.style.height = "20%";
var td = document.create Element('td');
var textarea = document.create Element('textar ea');
textarea.name = "inputDialo g";
textarea.id = "inputDialo g";
textarea.style. width = "100%";
textarea.style. height = "100%";
textarea.style. borderStyle = "ridge";
td.appendChild( textarea);
tr.appendChild( td);
tbody.appendChi ld(tr);
}
function menuItem (menuTitle)
{
var tr1 = document.create Element('tr');
tr1.style.backg roundColor = "blue";
var td1 = document.create Element('td');
var titleSpan = document.create Element('span') ;
titleSpan.style .color = "white";
titleSpan.style .fontWeight = "bold";
titleSpan.onCli ck = function() { alert('blah'); }
titleSpan.inner HTML = menuTitle;
td1.appendChild (titleSpan);
tr1.appendChild (td1);
tbody.appendChi ld(tr1);
var tr2 = document.create Element('tr');
var td2 = document.create Element('td');
td2.innerHTML = 'blah';
tr2.appendChild (td2);
tbody.appendChi ld(tr2);
}
initPage();
//****** CODE END ******

Many thanks.

Daz.

Nov 11 '06 #5
Daz

ASM wrote:
a question : is this table in a form ?
I take that back. Yes, the table IS going to be in a form. Either that,
or there will be several forms within the table. What made you ask?

Nov 11 '06 #6
VK

Daz wrote:
var titleSpan = document.create Element('span') ;
titleSpan.onCli ck = "this.toggle()" ;
titleSpan implements DOM interface which includes intrinsic [onclick]
event listener. This listener can be set to a function reference. In
case of click event the referenced function will be called. So the
first error: string instead of function reference.
The second error is that JavaScript is case-sensitive: unlike HTTP tags
and attribute names This way in your HTML source you use something
like:
<SPAN onClick="alert( this)">Text</span>
but in your JavaScript program the handler has to be named exactly as
it is: "onclick" (all lower case). Otherwise the program will decide
that you want to create new property "onClick" and assign a string
value to it (this is what it's doing). With all necessary corrections
the line will be:
titleSpan.oncli ck = function(){this .toggle();};
or (to keep the "stringifie d" approach):
titleSpan.oncli ck = new Function("this. toggle();");

Nov 11 '06 #7
ASM
Daz a écrit :
ASM wrote:
>IE would prefer :
textarea.name = "inputDialo g";
textarea.id = "inputDialo g";
Ok, I have changed this in my code. Thanks :)

I'd just like to point out that I don't have access to Internet
Explorer,
Anyway it is better for each browser.
>td.appendChild (textarea); // from inside
tr.appendChild (td); // to outside
table.appendCh ild(tr); // boxes
Ok, I have changed my code to reflect this. It makes more sense doing
it the way you suggested, although I was simply going by the examples
by Mark Kahn at
http://www.htmlgoodies.com/primers/j...le.php/3594621
I don't know this Mark :-)
But it seems to me we create elements that are virtual, then we append
them to their container, so it appears natural to do it from inside box
to the last outside one.
(even if modern browsers (FF) can understand what is the sens we adopt).
> p or span -td -tr -tbody -table -body
that is to show the design.
There are no body tags in my HTML.
If you have any tbody in your table, or any body in your html, the
browser will create them (at least in its mind) so you always can use them.
>perhaps :
titleSpan.oncli ck = function()
I have tried just doing:
No you haven't ! did you notice the c in lowercase ?
titleSpan.onCli ck = function() { alert('blah'); }
...and it still won't fire...
change your onClick in onclick and all will be OK.
>a question : is this table in a form ?
No, I'm not, and I don't plan to either. :)
If you use elements of form (input, textarea) you would have set them in
a form (simplest an cleanest : outside the table)

--
ASM
Nov 11 '06 #8
"Daz" <cu********@gma il.comwrote in news:1163250979 .382213.122970
@b28g2000cwb.go oglegroups.com:
Hello everyone. I am sure the answer to my question is simple, but I
can't seem to dynamically add an onClick event to my script.

I have a table which is generated dynamically, I am just struggling
getting an onClick event to show in the HTML source.
Two things. First, nothing dynamically generated will show up in your
source code. The source code is the document as rendered when
downloaded from the server. You *will* be able to see the changes in
the DOM structure using Firefox and its DOM-inspector (ctrl-shift-i) or
the Firebug addon.

Secondly, setting onclick (or any 'on') event to a script created DOM
element is a little tricky. You have to do it via a function.

http://p2p.wrox.com/topic.asp?TOPIC_ID=34541 (second post on the screen,
followup by OP)

see ya
Nov 11 '06 #9
Daz

ASM wrote:
Daz a écrit :
ASM wrote:
IE would prefer :
textarea.name = "inputDialo g";
textarea.id = "inputDialo g";
Ok, I have changed this in my code. Thanks :)

I'd just like to point out that I don't have access to Internet
Explorer,

Anyway it is better for each browser.
td.appendChild( textarea); // from inside
tr.appendChild( td); // to outside
table.appendChi ld(tr); // boxes
Ok, I have changed my code to reflect this. It makes more sense doing
it the way you suggested, although I was simply going by the examples
by Mark Kahn at
http://www.htmlgoodies.com/primers/j...le.php/3594621

I don't know this Mark :-)
But it seems to me we create elements that are virtual, then we append
them to their container, so it appears natural to do it from inside box
to the last outside one.
(even if modern browsers (FF) can understand what is the sens we adopt).
p or span -td -tr -tbody -table -body

that is to show the design.
There are no body tags in my HTML.

If you have any tbody in your table, or any body in your html, the
browser will create them (at least in its mind) so you always can use them.
perhaps :
titleSpan.oncli ck = function()
I have tried just doing:

No you haven't ! did you notice the c in lowercase ?
titleSpan.onCli ck = function() { alert('blah'); }
...and it still won't fire...

change your onClick in onclick and all will be OK.
a question : is this table in a form ?
No, I'm not, and I don't plan to either. :)

If you use elements of form (input, textarea) you would have set them in
a form (simplest an cleanest : outside the table)

--
ASM
Brilliant! onClick has been changed to onclick and now it's functioning
perfectly. Many thanks for your input. I have seen it as onClick on
many online examples. I am not sure why this might be, however, I now
know to use onclick. :)

Nov 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
18556
by: RobG | last post by:
I am trying to dynamically add an onclick to an element, however I just can't get the syntax right. consider the following function: function doClick (evt,x) { // do things with evt and x } Which is called statically by: <button onclick="doClick(event,this);">Click me</button>
3
12476
by: N. Demos | last post by:
How do you dynamically assign a function to an element's event with specific parameters? I know that the code is different for MSIE and Mozilla, and need to know how to do this for both. I have the following event handler functions defined and need to assign them to table elements (<TD>) created dynamically in another function. function handleMouseOver(elt, cssClass, strURL)
8
9537
by: cool2005 | last post by:
I tried to dynamically add/clone a <tr> from an existing <tr> to a <table> but the problem is that I need to have a "onclick" event handler in the <tr>. I have tried following A. approach 1. 1. find the <tr> that I will insert <tr>s right after it
4
2253
by: RobG | last post by:
I have a function whose parameter is a reference the element that called it: function someFunction(el) { ... } The function is assigned to the onclick event of some elements in the HTML source:
9
2198
by: Donius | last post by:
Hey everyone, i am doing some stuff where i'd like to pop up a little confirmation before a user clicks on a 'delete' link. Just trying to keep the markup clean, i added an attribute pre_act="confirm" to all of the links that i wanted to do this to and am trying to add an onclick event that will cancel the click action if they fail. I've got a test page at http://randomwebspace.net/testing/testpage.html. It has no unintentional XHTML...
7
2523
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written several methods that are working fine. The problem is if I want to dynamically assign an event handler to the object, the event handler is not called. What am I doing wrong? Below is a sample HTML doc with everything in place. <!DOCTYPE HTML PUBLIC...
3
3019
by: ICPooreMan | last post by:
The following is a very simple example of what I want to do take an elements oncontextmenu and changing it dynamically onclick of that same element. The code below will fail unless you change the line document.getElementById('div1').setAttribute('oncontextmenu', someText); to document.getElementById('div1').setAttribute('oncontextmenu', function(){alert('World World');return false;});
5
2296
by: tshad | last post by:
I found I can create Template columns dynamically - as long as I don't use objects that need onclick events, such as a LinkButton. Textboxes and Labels work fine. I create the Template columns like so: Dim column as TemplateColumn = new TemplateColumn() column.HeaderText = "Template Column" column.ItemStyle.Width = Unit.Pixel(width) column.HeaderStyle.Width = Unit.Pixel(width)
3
5253
by: Allen Chen [MSFT] | last post by:
Hi Richard, Quote from Richard================================================== However I also want to be able to remove the panes. I have tried to include this, but find that when I first add the pane the remove event does not get handled, though thereafter it is handled without problems. ==================================================
0
8246
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8368
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8231
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6652
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5404
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3895
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2383
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1476
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.