473,409 Members | 2,063 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,409 software developers and data experts.

dynamically add a table row with onclick

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
2. get content (collection of outerHTML of those <tr>s to be
inserted)
3. use insertAdjacentHTML to perform the inserting.

This approach failed with a "runtime error" at step 3. The code is
below
function loadSubRows222(tr_id) {

var doc = top.mainFrame.listFrame.document;
var table = doc.getElementById("tree_table");

//swDebugInfo(table.outerHTML, "1111");
var tb = table.children[0];
var trs = tb.children;
var sel = null;
var isEnd = false;
for (var i=0; i<trs.length; i++) {
if (trs[i].id==tr_id) {

if (i==trs.length-1) {
isEnd = true;
} else {
sel = trs[i];
}
break;
}
}
if (sel==null && !isEnd) {
alert("Selected row not found.");
return;
}

var pn = doc.getElementById(tr_id);
pn.loaded = '1';
var doc2 = top.hiddenFrame.document;
var table2 = doc2.getElementById("subListTable");
//swDebugInfo(table2.outerHTML, "hiddenFrame.document");
var tb2 = table2.children[0];
var ttt = tb2.innerHTML;
sel.insertAdjacentHTML("afterEnd", ttt);
}

B. Approach 2.

1. find the <tr> that I will insert <tr>s right after it
2. create a <tr> using createElement("tr"), say newTr
3. assign outerHTM of the new <tr> content to newTr's outerHTML
(I have to use outerHTML instead of innerHTM since I need to
carry the onclick)
This failed too with the "runtime error" when assign outerHTML

C. approach 3
1. find the <tr> that I will insert <tr>s right after it
2. create a <tr> using createElement("tr"), say newTr
3. copy/construct the newTr copyTr (see below)
trying to assign onclick as a field of newTr failed
since the "onclick" was not recongnized as an event
handler.

function copyTr(doc, t1, t2) {

t1.id = t2.id;
t1.loaded = t2.loaded;
t1.level = t2.level;

//get the content of onclick
var oStr = t2.outerHTML;
var i=oStr.indexOf(" onclick=\"");
var j=oStr.indexOf("\"", i+10);

//assignment
t1.onClick = oStr.substring(i+10, j);
var ch = t2.children;
for (var i=0; i<ch.length; i++) {
var newTd = doc.createElement("td");
newTd.innerHTML = ch[i].innerHTML;
t1.appendChild(newTd);
}
}

My target is IE.

Any suggestion will be very appreciated.

thanks

Jul 23 '05 #1
8 9487


cool2005 wrote:
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>.


How about
var newRow = oldRow.cloneNode(true);
and if the onclick handler is really missing then doing
newRow.onclick = oldRow.onclick;
If you don't want to copy the onclick but create a new one then make
sure you assign a function object e.g.
newRow.onclick = function (evt) {
// code goes here
};
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
cool2005 wrote:
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
2. get content (collection of outerHTML of those <tr>s to be
inserted)
3. use insertAdjacentHTML to perform the inserting.

This approach failed with a "runtime error" at step 3. The code is
below


Inserting HTML into a table element to create a new TR will modify
the table's innerHTML property, which is read-only in IE:

"...the innerText and innerHTML properties of the table and tr
objects are read-only."

<URL:http://msdn.microsoft.com/workshop/author/tables/buildtables.asp>

The following also in regard to innerHTML:

"The property is read/write for all objects except the following, for
which it is read-only: COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE,
TBODY, TFOOT, THEAD, TITLE, TR. The property has no default value."

<URL:http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/innerhtml.asp>

You can use innerHTML to modify the content of a cell (TR), but
generally it is better to use DOM methods unless you are just doing
something simple like replacing text.

As Martin suggested, the simplest way to create a copy of an existing
row is with cloneNode. The following example clones the last row in
the table and adds a new clone after it (tested in IE and Firefox).
I've included a document.all method, but I'm not sure how well
cloneNode is supported by older versions of IE that require it.
<script type="text/javascript">
function cloneRow(t){
if (document.getElementById( {
t = document.getElementById(t);
} else if (document.all) {
t = document.all[t];
} else { return;}

if (t.nodeName && 'TABLE' == t.nodeName){
var oldRow = t.rows[t.rows.length - 1];
var newRow = oldRow.cloneNode(true);
oldRow.parentNode.insertBefore(newRow, oldRow.nextSibling);
}
}
</script>

<input type="button" value="Add another row by cloning"
onclick="cloneRow('tableA')">
<table id="tableA">
<tr onclick="alert('hi from row ' + this.rowIndex)";>
<td>Click this to activate the tr onlcick</td>
</tr>
</table>

A word of caution: the element and its content are cloned exactly, so
if the tr has an id, the new row will have an identical id. You
should change it before adding it to the table.

Similarly, any enclosed form or other elements will be cloned exactly
too, so you may need to change their ID or NAME also as appropriate.

Lastly, when adding TR elements to a table, IE requires you to add
them to the tbody, not the table (HTML 4 conforming browsers will add
a tbody element regardless if it's been coded in the HTML). In the
code above, I've avoided the issue by adding the new row to the
parent of the old row.

Another approach would be to put the id on a tbody element and add
the new row to that.

...
if (t.nodeName && 'TBODY' == t.nodeName){
var oldRow = t.rows[t.rows.length - 1];
var newRow = oldRow.cloneNode(true);
t.insertBefore(newRow, oldRow.nextSibling);
}
...

<table>
<tbody id="tableA">
<tr onclick="alert('hi from row ' + this.rowIndex)";>
...

[...]
--
Rob
Jul 23 '05 #3

RobG wrote:
[...]
You can use innerHTML to modify the content of a cell (TR), but


Cells tags are <TD> or <TH> of course...

[...]

--
Rob

Jul 23 '05 #4
The cloneNode won't work in my case.
The <tr> I cloned from resided in a hidden frame.
The "onclick" in new <tr> (from cloning) worked until
the hidden frame is resubmit (means the content of
the hidden frame was changed - the <tr> as the cloned source
was gone). It looks like that the new cloned <tr> still have some
sort of connection to the <tr> it was cloned from. The "onclick"
worked only when the source <tr> existed.

Let me redescribe my problem:

I want to create a <tr> with a variable "onclick" (varible means
the onclick contains row dependent info - can not be defined
as a static "function" - function doesn't help since the arguments
are row dependent). I actually need to "clone or create" this <tr>s
from a
hidden frame returned from the server.

The problem is that I can not assign the outerHTML that include the
"onclick" to a created new <tr> nor set "onclick" as an attribute.

I really appreciate the suggestions from both of you.

Any further thought?

thanks

Jul 23 '05 #5
I forgot to mantion:

After cloning I tried to use insertBefore and failed with a
error of "invalid argument":

for (var i=0; i<trs2.length; i++) {
newTr = trs2[i].cloneNode(true);
tb.insertBefore(newTr, sel);
sel = newTr;
}
where sel is the row to insert before and trs2[i] is the
<tr> in the hidden frame to clone from.

Then I tried insertAdjacentElement as

for (var i=0; i<trs2.length; i++) {
newTr = trs2[i].cloneNode(true);
sel.insertAdjacentElement("afterEnd", newTr);
sel = newTr;
}
in this case sel is the one to be inserted after.
The "onclick" worked after the statements above.
But it won't work if I do

for (var i=0; i<trs2.length; i++) {
newTr = trs2[i].cloneNode(true);
sel.insertAdjacentElement("afterEnd", newTr);
sel = newTr;
}

refreshHidden();

Any suggestion will be appreciated

Jul 23 '05 #6
OK, problem solved: I was able to create a function and passed
row related info with "this" and used "this" as the only argument to
make the onclick the same for all rows.

I then cloneNode from the same table and changed cell info.

The key help is the cloneNode!

thanks a lot!!

Jul 23 '05 #7
cool2005 wrote:
I forgot to mantion:

After cloning I tried to use insertBefore and failed with a
error of "invalid argument":

for (var i=0; i<trs2.length; i++) {
newTr = trs2[i].cloneNode(true);
tb.insertBefore(newTr, sel);
sel = newTr;
}
Seems you got it working, but for the record if you are just inserting
after the current rows (assuming tb is the tbody and that trs is the
collection of rows you are cloning):

for (var i=0, j=trs2.length; i<j; i++) {
tb.appendChild(trs2[i].cloneNode(true));
}

or

var i=0;
do {
tb.appendChild(trs[i].cloneNode(true));
} while(trs[++i]);

[...]
Any suggestion will be appreciated


--
Rob
Jul 23 '05 #8
RobG wrote:
<snip>
... (HTML 4 conforming browsers will
add a tbody element regardless if
it's been coded in the HTML).

<snip>

In HTML 4 the opening and closing TBODY tags are optional, so their
absence from source mark-up is irrelevant, the mark-up still specifies
the creation of a TBODY element. The TBODY _is_ coded in the HTML by the
act of placing a TR directly inside a TABLE.

Richard.
Jul 23 '05 #9

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

Similar topics

3
by: KathyB | last post by:
Hi, I'm trying to find a way to validate input text boxes where I don't know the names until the page is rendered. I've got 2 validate functions that fire with the onsubmit button of a "mini" form...
4
by: Terry | last post by:
I have a number of input boxes used to display totals based on selected items for each row in a table. There are more than a few rows that are identical, except for the form field name. I have...
0
by: Diane Yocom | last post by:
I'm very new to ASP.Net and probably jumped in a little over my head, but... I'm trying to create a user control that will control navigation through my site. It's sortof like Amazon.com, where...
5
by: Dennis Fazekas | last post by:
Greetings, I am creating a web form which will all the user to add an unlimited number of email addresses. Basically I have 3 buttons, "Add Another Email", "-" to remove, and a "Save" button....
1
by: vj | last post by:
How i can populate all fileds dynamically in jsp page based on contents found in xml file? I have written jsp servlets and java class file. i transferred automatic data from jsp to servlet then to...
0
by: vijendra | last post by:
How i can populate all fileds dynamically in jsp page based on contents found in xml file?I have written jsp servlets and java class file. i transferred automatic data from jsp to servlet then to...
11
by: Daz | last post by:
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...
2
by: jmarendo | last post by:
Hello, After reading through the "Table Basics - DOM - Refer to table cells" example at mredkj.com , I modified the code for my own purposes. In the modified version, I create a hyperlink and...
7
by: moksha | last post by:
Hi, I am new to javascript and i am facing a problem in coding. plz help me out. I am using javascript for dynamically creating a table row which contains text boxes and radio...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
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...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.