473,725 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

adding/deleting dynamic table row, rowIndex

I am trying hard for days now to add and delete rows to a table. I
could really use some help...

Each row contains two buttons (images) - 'add row' and 'delete row'.
When the user clicks add row within a specific cell/row, the index of
that row should be passed to a function that creates a new row using
that index (the new row should be added directly below the row where
the user clicked. The new row should contain all of the cells and html
in the cells from the row above, including the buttons/images. If a
user clicks delete row, the index of the row with the delete button
should pass to the function that deletes the row.

I would greatly appreciate any help - I'm new to this. The more
thorough the explanation, the better. I've seen the other postings in
this group and I can't seem to apply the logic to my situation.

THANKS

Jul 23 '05 #1
10 22225
AdamG wrote:
I am trying hard for days now to add and delete rows to a table. I
could really use some help...


You probably want to use cloneNode, some code follows. Be aware that
you will also clone any element ids or names too. Post again if you
need further help.
<html><head><ti tle>Add & Delete Table Rows...</title>

<script type="text/javascript">

/* cloneRow
* Clones a row when a cell has been clicked on
* Given a reference to the cell, clones the row and inserts it
* before nextSibling.
* If the nextSibling doesn't exist, it doesn't matter, the
* newElement is put immediately after the the row theThing is
* in anyway.
*/
function cloneRow(theCel l) {
if( document.create Element && document.childN odes ) {
var thisRow = theCell.parentN ode;
var newElement = thisRow.cloneNo de(true);
thisRow.parentN ode.insertBefor e(newElement,th isRow.nextSibli ng);
}}

/* deleteRow
* Deletes a row when a cell is clicked on.
* Gets a reference to the row that the cell is in, then deltes the
* entire row from the table.
*/
function deleteRow(theCe ll) {
if( document.create Element && document.childN odes ) {
var thisRow = theCell.parentN ode;
thisRow.parentN ode.removeChild (thisRow);
}}

</script>
</head>
<body>

<table border="1">
<tr>
<td onclick="cloneR ow(this);">Clic k here to clone the row</td>
<td>here is another cell</td>
<td onclick="delete Row(this);">Cli ck here to delete the row</td>
</tr>
</table>

</body></html>

--
Rob
Jul 23 '05 #2
On 8 Dec 2004 12:17:09 -0800, AdamG <ag*******@yaho o.com> wrote:

[snip]
When the user clicks add row within a specific cell/row, the index of
that row should be passed to a function that creates a new row using
that index (the new row should be added directly below the row where the
user clicked.
Table rows contain, amongst other properties, two named rowIndex and
sectionRowIndex . The former specifies the position within the table as a
whole. The latter specifies the position within the containing table
section: an implicit or explicit TBODY, THEAD or TFOOT element.

To get those values when a button within the row in question is activated,
use:

var button, cell, row;
if((cell = button.parentNo de) && (row = cell.parentNode )) {
return row.rowIndex; // or row.sectionRowI ndex
}

The easiest way to obtain a reference to the button is to use the this
operator inside the click event. I'll show that later.

It's probably obvious, but the number obtained from the rowIndex property
should be used with the table's insertRow and deleteRow methods, whilst
rowSectionIndex should be used with a table section's insertRow and
deleteRow methods.
The new row should contain all of the cells and html in the cells from
the row above, including the buttons/images.
That's simple enough. Calling

row.cloneNode(t rue)

will return a new row which contains everything the original did. However,
you'll have to add event listeners again as they're not copied.
If a user clicks delete row, the index of the row with the delete button
should pass to the function that deletes the row.


This will follow on from the insertion code.

[snip]

In all, you're probably looking at:

function remove(btn) {var cell, row, sect;
if((cell = button.parentNo de) && (row = cell.parentNode )
&& (sect = row.parentNode) && sect.deleteRow)
{
sect.deleteRow( row.sectionRowI ndex);
}
}

function insert(btn) {var cell, newRow, row, sect;
if((cell = button.parentNo de) && (row = cell.parentNode )
&& row.cloneNode && (sect = row.parentNode)
&& sect.insertBefo re)
{
newRow = row.cloneNode(t rue);
/* If you need to alter the new row
* or its contents, do it here.
*/
sect.insertBefo re(newRow, row.nextSibling );
}
}

You'd call these with:

<input type="button" ... onclick="insert (this);">

and

<input type="button" ... onclick="remove (this);">

If you need more help, you'll have to show the relevant HTML you're using.

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
On Thu, 09 Dec 2004 07:56:24 +1000, RobG <rg***@iinet.ne t.auau> wrote:

[snip]
if( document.create Element && document.childN odes ) {
Umm, what relevance does document.create Element and document.childN odes
have to the methods and properties you're using?
var thisRow = theCell.parentN ode;
var newElement = thisRow.cloneNo de(true);
thisRow.parentN ode.insertBefor e(newElement,th isRow.nextSibli ng);


Test what you're actually using: don't infer. Even complete feature testing

function cloneRow(cell) {var row, section;
if((row = cell.parentNode ) && row.cloneNode
&& (section = row.parentNode) && section.insertB efore)
{
section.insertB efore(row.clone Node(true), row.nextSibling );
}
}

won't adversely affect the speed of execution to any noticable level.
However, it is probably (fairly) safe to assume that is a property that
exists on one node will exist on another.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
A few more hints, I have a tad more time at the moment.

A useful enhancement is to prevent the last row of the table from being
deleted. Get the parent of the row (which should be a tbody) and count
the rows:

var numRows = theRow.parentNo de.rows.length;

if numRows <= 1, don't allow the user to delete the row. To make
sure it all works, it is probably best to put tbody elements in your
HTML. That's a belt and braces approach I guess, but removes any doubt
as to what the row parent is (read: simpler maintenance).

And a few thoughts on cloneNode:

A common use for cloneNode is when you have a form set out in a
table, like a purchase order with many inputs in each row. cloneNode
allows you to simply create another line in the form and includes any
user input too, potentially saving user input keystrokes.

It may be useful to create a function that goes through the cloned node
and selectively removes some (or all) user input that has been cloned.

A downside of using cloneNode is that you now have identical element
ids/names. If you are allowing users to add and delete new elements
in no particular order this can be a real issue.

When submitting the form, you will get multiple name/value pairs with
the same name - which can be handled OK at the server as all the
parameters are passed in sequence (though I'm not sure you can
guarantee the sequence, so don't depend on it). The real grief is when
you try to validate the form, as you can't uniquely identify elements
with identical names other than by their order in the form.

And if you clone an entire form, how do you identify one from another?

And of course there is the syntactical correctness issue of creating
invalid markup by having identical ids.

So you need to develop a scheme for creating unique ids and names and
attaching them to the elements - it can be labourious and kinda defeats
the beautiful simplicity of cloneNode, but may still be better than
creating it all from scratch.

Mike Winter shows where to do it in his post.

Provided you can overcome these issues, cloneNode is a great invention.

--
Rob
Jul 23 '05 #5
Michael Winter wrote:
[...]
Umm, what relevance does document.create Element and document.childN odes
have to the methods and properties you're using?

[...]

Err, excellent point. This was from some old code that I didn't clean
up properly - rushing between assignments at the moment.

My apologies to the OP and thanks to Mike. :-p

--
Rob
Jul 23 '05 #6
You guys have given me some fantastic advice. Thanks! I'm trying it
all right now.

I am concerned about not having unique element IDs when I use
cloneNode.

Thanks!!

Jul 23 '05 #7
What about using insertRow and innerHTML for each cell, instead of
using cloneNode? Would this create unique IDs for the elements?

Jul 23 '05 #8
On 9 Dec 2004 07:37:04 -0800, AdamG <ag*******@yaho o.com> wrote:
What about using insertRow and innerHTML for each cell, instead of using
cloneNode? Would this create unique IDs for the elements?


No. If you can show *exactly* what a row will contain and how you'd like
to change its contents, we can give you an answer.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9
Hi - I tried you code above. I was able to get it working - I had to
change one thing :

if((cell=btn.pa rentNode)..... I changed "button" to "btn", to
correspond to the parameter passed to the function (btn).

I'm now thinking about ways to make each row element unique for the
purposes of submitting the form. Any ideas on how I could submit the
results (I'm sure you have ideas). Again THANK YOU !!!!!!!!!!!!!!! !!!!

Jul 23 '05 #10

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

Similar topics

6
6488
by: Brendan.Collins | last post by:
Hi I have a javascript problem that has been annoying me for two days now and thought that a javascript expert might have the magic solution. I am populating a table dynamically from the database and I am trying to allow the user to order the rows in the table using up and down arrows. The function I am using is:
1
2234
by: Klom Dark | last post by:
I've got a weird problem going on - I've got a table of dynamically created buttons. Each button has the X/Y value of the buttons position in the table assigned to it's CommandArgument property and the name of a common command (btn_Command) assigned to it's Command property. The creation of the table is done by a function called drawGeo. drawGeo is called during the initial Page_Load (!IsPostBack), but should be called by btn_Command on...
5
1694
by: Klom Dark | last post by:
I'm trying to figure out how to get a table of dynamically created buttons to actually call the command associated with it. It never seems to work, but doing more research it looks like I may need to implement IPostBackEventHandler. However, I cannot find any examples of doing so. Does anyone have an example of using IPostBackEventHandler/RaisePostBackEvent with an array of controls?
1
2031
by: seanmayhew | last post by:
I have a form page that that while editing saves the data to an xml doc before submitting to db. On each page unload it saves the xmldoc as the user can add multiple items to the company like product types etc. So for instance Im adding a fruit company while adding a fruit company I allow the user to add types of fruit they carry and display it dynamically using an <asp:table> with image
5
2488
by: JonH | last post by:
Ok, I have this dynamically created table in my one of my php forms that shows the names of the people the user has entered into a text field. When they hit add a row displays, showing the name they entered. Also, an image that allows them to delete shows beside the name upon creation. The delete removes the name from the table and pushes the other names to the top. Simple stuff, however, if I delete the last name displayed(the bottom of...
1
1332
by: Dhruba Bandopadhyay | last post by:
I know that JavaScript lets us add: ondragenter, ondragover, ondragleave, ondrop events to normal HTML table td tags. This lets us do highlighting of table cells/rows, and capture drag & drop events. So to handle ondrop we can use JavaScript: this.OnDrop = function(obj) { obj.parentElement.style.backgroundColor = "white";
2
2137
by: philin007 | last post by:
Hi Guys, Could any one help me out with codes to add rows to a table. Well I kinda of got the codes from the following site (http://www.interviewboard.com/DHTMLSamples/DHTMLGridSample.htm) the problem is this example only shows input box. Now i have a list that means a 'select box' for which the value is retrieved from Database and populated into the select list box. Now according to the example if all residing in the javascript how am i...
17
5558
by: cygsoft | last post by:
Hi I have created a dynamic row and inserted the values into the cells of those rows from textboxes. Now I have to edit those values stored in the rows. At the end of each row created dynamically two buttons namely "Edit" and "Delete" are present. If I click the "Edit" button the values in that particular cells should go back to the textboxes for editing and then after editing it should go to the corresponding place. Can any one help to...
1
3258
by: kanishka1213 | last post by:
#!/activeperl/perl/bin/perl use CGI qw(:standard); print "Content-type: text/html\n\n"; print <<EndOfHTML; <html> <head> <script language="javascript" type="text/javascript">
0
9401
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
9257
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...
0
9111
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
8096
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
6011
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
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.