mredkj.com logo

An update blog for mredkj.com

What's this blog about?

mredkj.com is an unfocused programmer resource from Matt, Eric, and Keith

This blog will keep you up to date with our latest site changes.

Thursday, May 26, 2005

Update - Table add row

tableaddrow.html

I added code to associate an event with the new text inputs. A couple people had emailed about this.

posted by Keith [5/26/2005 10:52:00 PM] - permalink - 88 comments

88 comment(s):

Anonymous Anonymous wrote:

hi! i'd like to know how you can edit the cells like put color into them and make them follow a certain css. thanks! :)

Posted [8/11/2005 10:22:00 PM]  

Blogger Keith wrote:

If you want the table to follow a certain css, then you can do that with a document-level style sheet.

For example, the following would go either in the head between style tags, or in an external css file:
#tblSample tr td { background: #c77; }

In that example, for the table tblSample, the td elements will be styled with a background color.

There are other ways of implementing style sheets, but that's a topic for another discussion.

One thing, though. If you must apply a style to a specific element (and it's usually not necessary), try the following:

btnEl.style.backgroundColor = 'blue';
btnEl.style.color = 'white';

Posted [8/12/2005 03:53:00 AM]  

Anonymous Anonymous wrote:

i'm using this in a form which submits to a php page, but i can't seem to pick up any of the rows after the first.. is this possible?

Posted [8/15/2005 07:06:00 AM]  

Blogger Keith wrote:

"i'm using this in a form which submits to a php page, but i can't seem to pick up any of the rows after the first.. is this possible?"

In the tableaddrow page, the example does what you're asking. Refer to method addRowToTable to add an id to the new input box, and refer to method validateRow to refer to a newly added input box.

If you're still having problems, could you please post example code.

Posted [8/15/2005 06:29:00 PM]  

Anonymous Anonymous wrote:

how do you post code on here? i can't get it to accept my example...

Posted [8/30/2005 12:57:00 PM]  

Blogger Keith wrote:

The blogger instructions above the comment box says "You can use some HTML tags", which I assume means you can't use most tags that could be harmful.

If you're going to post a javascript example, then it will probably be enough just to post the portion of the code you have a question about.

Posted [8/31/2005 03:30:00 AM]  

Blogger Keith wrote:

For anyone that has PHP on the backend and wants to try a simple example in conjunction with my addrow javascript, the following will print out the row values submitted.

$i = 1;
$rowName = "txtRow".$i;
while (isset($_POST[$rowName])) {
echo $_POST[$rowName]."<br />";
$i = $i + 1;
$rowName = "txtRow".$i;
}

I'm no PHP expert, so maybe there's a better way to do this.

Posted [8/31/2005 04:06:00 AM]  

Anonymous Anonymous wrote:

ach, it's a combination of javascript, html and php... my php code is similar to what you have put there, i will have another go at simplifying it down and see if it works.. i'll get back to you in a bit, thanks a lot!

Posted [8/31/2005 08:32:00 AM]  

Anonymous Anonymous wrote:

Bizarrely, the current situation is:

I have a test page (PHP) containing just the table add-row code (picking up the values using the PHP code you gave earlier), which works on both IE and Mozilla Firefox

I have the exact same code within a larger PHP page, which works on IE but not Firefox! This only picks up the first value in the table - even when i hard-coded the form-processing page to get txtRow1, txtRow2, txtRow3 etc, this didn't work.. so evidently the problem is that these are somehow not getting passed properly.

To be honest, I have no idea how to fix this and it's making me crazy! Any ideas... ?

Posted [9/09/2005 05:50:00 AM]  

Blogger Keith wrote:

Some possibilities for a submit not working properly:

* No form element defined (i.e. You have input elements but no form tags wrapping it)

* No name attributes for the input elements.

* Conflicting names.

* A typo someone in your code.


When debugging, it's sometimes useful to test out variations of the code that get you closer to the working code.

Depending on how anonymous you want to remain, you could send me your HTML/javascript (not the PHP) (Email is listed in the mredkj About Us page)

Posted [9/09/2005 09:25:00 AM]  

Anonymous Anonymous wrote:

All table tags must by inside form tags. If <FORM> tag is after tag <TABLE>, php backend works on IE but not on Firefox and Opera.

Posted [9/27/2005 04:39:00 AM]  

Blogger Keith wrote:

You have a lot of questions, myusernameisthis. Some of them would be a lot of work to answer, so I'll see if I can guide you in the right direction.

change the output tags

I'm not sure where you're getting anything named textitem1 and textitem2, because when I tried your demo, the submit opened up a window with fields named txtRow1 and txtRow2. Assuming that's what you're talking about, then what you need to change is the lines such as
Regel.setAttribute('name', 'txtRow' + iteration);

Change 'txtRow' to whatever you want. Do the same for the other cells. I recommend changing every name and id to be unique, including the ones in the original HTML.

changing it to reflect drop downs

The code in your page seems to have some attempts at adding drop downs, but I wouldn't recommend using createElement to add options. I have a few tutorials dealing with Select elements, such as tutorial006.html. The code is more advanced than what you need, so here's a simple implementation you can try.

function addOption(theSel, strText, strValue)
{
theSel.options[theSel.length] = new Option(strText, strValue);
}

You would use it like:
var selTest = document.createElement('select');
addOption(selTest, 'theText1', 'theValue1');

pre-populate the drop downs with data from a DB

How do you plan on loading the data in the first row's drop down? Will each row be the same? If that's the case, then scratch what I said before with the whole addOption function thing. What you'd do is to clone the first select.

In your code, you have a bunch of statements for each drop down. Replace each one with something like:

var cellEmp = row.insertCell(0);
var selEmp = document.getElementById('sel1').cloneNode(true);
selEmp.setAttribute('name', 'selNewName' + iteration);
cellEmp.appendChild(selEmp);

Make sure you change the id of the existing HTML drop down to sel1 (or use whatever you want, but make them match).

Another thing. You might want to take out all the unnecessary code from my original tutorial. I get the feeling you're not using all of it.

Posted [10/21/2005 12:04:00 AM]  

Blogger Keith wrote:

myusernameisthis said, "is there a way to pass over how many rows that where dynamically created in total?"

Short answer: Put the iteration variable into a hidden field.

Long answer: Well, when it comes to my JavaScript examples, I try not to get into long answers that involve server-side problems. I know this is a client-side question, but you really need to consider both sides.

In this case, you're asking for a row count. So, my first question is: why do you need a count sent, when you can determine it yourself on the server-side.

Depending on what your end goal is, you might be able to use the PHP code I posted earlier in this blog entry that allows you to loop and get all the row values without knowing the count ahead of time. Refer above to the comment where I say "I'm no PHP expert"

Posted [10/23/2005 10:28:00 PM]  

Anonymous Anonymous wrote:

I am using Perl to write the html, how do I write the number of lines (iterations) out to the html so I can pick it up with a "param" stmt? I would use this value to loop through to pick up all the values of each cell.

Posted [11/30/2005 10:00:00 AM]  

Blogger Keith wrote:

"how do I write the number of lines (iterations) out to the html so I can pick it up with a "param" stmt?"

I'll have to look into this further.

On the one hand, maybe there's something I can do on the client side (the javascript) to make it easier to get the values on the server side. The current code names all the elements a different name, where maybe it would be better if they were named the same thing, and let the server side pick it up as an array. I think that would cause some differences in the html for languages like PHP where array names need to be specified with brackets [], so for now I'm trying to avoid that.

On the other hand, you might be able to handle your question entirely on the server side while using the javascript addRowToTable I have up now.

I was able to get a simple PHP example working. Take a look at the blog post I made above that includes the line:
while (isset($_POST[$rowName])) {

I did some brief research, and it seems Perl has an isset statement.

Posted [11/30/2005 10:25:00 AM]  

Blogger Keith wrote:

Also, to address your specific question. If you think the easiest way to accomplish what you want is to send the row count, then you can set the value of a hidden input.

I don't have an example of using addRowToTable like that, but I have some hidden input code in:
http://www.mredkj.com/tutorials/tutorial007.html

Posted [11/30/2005 10:42:00 AM]  

Anonymous Anonymous wrote:

I did add a hidden var like this:
var max = document.createElement('input');
max.setAttribute('type', 'hidden');
max.setAttribute('name', 'MAX');
max.setAttribute('value', iteration);

Is this really going to create a hidden var with the number of lines?

in perl:
$max = param("MAX");

Posted [11/30/2005 11:29:00 AM]  

Blogger Keith wrote:

"Is this really going to create a hidden var with the number of lines?"

You'll need to append the new element to the form, or to an element in the DOM of the form.

For example (given the form has an id of frm1):
var x = document.getElementById('frm1');
x.appendChild(max);

Posted [11/30/2005 06:58:00 PM]  

Anonymous Anonymous wrote:

I was following your example for writing a input statement back to the form. I will try what you suggest.
Thanks,

Posted [12/01/2005 03:50:00 PM]  

Anonymous Anonymous wrote:

hi there, can you help please??

one: the name here
selOpDate.setAttribute('name', 'OpertorDate');
txtInpDate.setAttribute('name', 'txtDate');
in the output: it show just the id but name the like T1,T2.. and so on
this for all input type??

2:I have a Date text and a button,
the code:
// cell 2 - input text
var celltxtDate = row.insertCell(2);
var txtInpDate = document.createElement('input');
txtInpDate.setAttribute('type', 'text');
//(How to make it readOnly);
txtInpDate.setAttribute('name', 'txtRow' + iteration);
txtInpDate.setAttribute('id', 'txtpropName');
txtInpDate.setAttribute('size', '40');
txtInpDate.setAttribute('value', ''); celltxtDate.appendChild(txtInpDate);
// cell 3 - input button
var cellbtnCal = row.insertCell(3);
var btnCal = document.createElement('input');
btnCal.setAttribute('type', 'button');
btnCal.setAttribute('value', 'Calander');//here how to put an image??
btnCal.onclick = function () {funViewCalender()};
cellbtnCal.appendChild(btnCal);
in the function funViewCalender() how to asign it to cell 2(txtInpDate)

Posted [12/07/2005 06:18:00 AM]  

Blogger Keith wrote:

"in the output: it show just the id but name the like T1,T2.. and so on
this for all input type??"

I don't understand the question.

"//(How to make it readOnly);"

See my answer in the HTML Table Delete Row blog entry.

"here how to put an image??"

"in the function funViewCalender() how to asign it to cell 2(txtInpDate)"

I don't have a quick answer for those. I'll look at it in the next day or so.

Posted [12/07/2005 09:19:00 AM]  

Anonymous Anonymous wrote:

hi keith,
reg table add rows
i want to get the value that is entered in the cell, If so how can I do this?

Posted [12/16/2005 01:54:00 AM]  

Blogger Keith wrote:

"i want to get the value that is entered in the cell"

Take a look at my Reference Dynamic Rows tutorial. It should do what you want.

Posted [12/16/2005 08:51:00 AM]  

Anonymous Anonymous wrote:

Your html + javascript is excellent. I want to store the data which is displaying on tableaddrow_nw.html in mysql database with php scripting.

tableaddrow_nw.html is displaying characters like,
%2C+ for space and all. How to remove those?

Posted [12/22/2005 05:29:00 AM]  

Blogger Keith wrote:

"tableaddrow_nw.html is displaying characters like, %2C+ for space and all."

My example is only client-side, but if you submit to a PHP page and use $_GET, the value will be unescaped automatically.

Also, you may want to switch the form submit to method="post", and when you read the values in your PHP page use $_POST

FYI, for anyone who is doing a client-side example (no PHP, ASP, etc.), and wants to manually unescape the values of a "get" submit, try using the decodeURI method.

Posted [12/22/2005 09:05:00 AM]  

Anonymous Anonymous wrote:

Thanks. Keith,

I need one more help on how to use select statement with createElement() function.

select name=select
option value="c"C
option value="1"1
option value="2"2
option value="3"3
option value="4"4
/select

Add < > in the statement.

This is static select. I want to use this for three tables. How to use with var boxInp = document.createElement('select'); statement.

I have referred http://www.mredkj.com/tutorials/tutorial006.html. However it is different from what I am looking for.


Thank You.

Posted [12/23/2005 03:47:00 AM]  

Blogger Keith wrote:

"How to use with var boxInp = document.createElement('select'); statement."

Does the example in my tutorial Reference Dynamic Rows help? Specifically look at the appendRow function in tablebasics2.js.

Posted [12/23/2005 09:17:00 AM]  

Anonymous Anonymous wrote:

this is a great tutorial, with great comments. i'd like to ask you about the comment you mentioned about naming the fields the same thing and passing it serverside(php) as an array. this is exactly what i am wanting to do. have each row contain 7 fields...each part of an array something like "$line[0][name], $line[0][date], ..., $line[1][name], $line[1][date], ..."
do you have any suggestions on an easy way to do this?

Posted [2/06/2006 02:08:00 PM]  

Blogger Keith wrote:

have each row contain 7 fields...each part of an array something like "$line[0][name], $line[0][date], ..., $line[1][name], $line[1][date], ..."

When I was talking about arrays in an earlier comment, I was talking about them ending up like:
yourdate[0], yourdate[1]
yourname[0], yourname[1]
etc.

To do that, for every form column, name it like yourdate[]

I'm not sure how to do what you're asking, which is to have a multi-dimensional array being passed server-side.

Posted [2/07/2006 12:02:00 AM]  

Blogger Keith wrote:

musi said: how do i set onBlur and onFocus to the dyanmic generated rows

The events are case-sensitive. Use onblur and onfocus

Posted [2/07/2006 12:02:00 AM]  

Anonymous Anonymous wrote:

Keith,
Yeah, I tried setting the name attribute to 'line[' + iteration +']' I also tried 'line[' +iteration+'][name]' but neither worked as expected. it just seemed like nothing was passed back. i may just end up going with different names with each field concatenated with the iteration on the end like "name0,name1,name2,name3"

Posted [2/07/2006 09:28:00 AM]  

Anonymous Anonymous wrote:

Hi.. Your code is very useful for me. But i a little problem when using ur code. I just want to ask u, how can i past an input of textfield into a database(every row). I'm currently using php..

Posted [2/21/2006 08:54:00 PM]  

Blogger Keith wrote:

Anonymous said...
"how can i past an input of textfield into a database(every row)"

That's beyond the scope of this tutorial. It might be a good project for me to do sometime in the future.

Posted [2/22/2006 12:52:00 AM]  

Anonymous Anonymous wrote:

I NEED TO HAD A CSS CLASS TO A TEXT FIELD EXAMPLE

var cellRight = row.insertCell(1);
var e2 = document.createElement('input');
e2.setAttribute('type', 'text');
e2.setAttribute('name', 'txtiTEMS');
e2.setAttribute('id', 'txtISOCom' + iteration);
e2.setAttribute('class', 'txtbox1');


IS IS NOT WORKING CAN ANY ONE HELP ME IN THIS

Posted [2/27/2006 02:33:00 AM]  

Anonymous Anonymous wrote:

This comment has been removed by a blog administrator.

Posted [2/27/2006 02:34:00 AM]  

Blogger Keith wrote:

Anonymous wrote:
"I NEED TO HAD A CSS CLASS TO A TEXT FIELD EXAMPLE"

I removed your redundant comment.

To answer your question, use the syntax:
e2.className='nameofclass';

Refer to the tabledeleterow.js source code linked from my HTML Table Delete Row example, where I apply different CSS classes to alternating rows.

Posted [2/27/2006 09:18:00 AM]  

Anonymous Anonymous wrote:

I add onfocus in the addRowToTable() function


var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.onfocus = alertunit();
el.size = 40;


then I add another fuction:
function alertunit() {alert("alert onFocus calculate");}

It didn't work. can you help me fig out. thanks

Posted [4/04/2006 11:22:00 PM]  

Anonymous Anonymous wrote:

sorry,typing mistake

the line:
el.onfocus = alertunit();
should be:
el.onFocus = alertunit();

I want the onFocus function should work,when everytime the mouse in the textrow box

Posted [4/04/2006 11:49:00 PM]  

Blogger Keith wrote:

First, go back to lowercase - onfocus. Next, take away the parenthesis.

el.onfocus = alertunit;

For an explanation of that technique of registering an event handler, refer to this quirksmode.org page

Posted [4/05/2006 03:06:00 AM]  

Anonymous Anonymous wrote:

thanks, it works well now!!

Posted [4/05/2006 08:48:00 AM]  

Anonymous Anonymous wrote:

Hi, I have problem with pass php array to javascript function.

the JavaScript:
function listItems(itemList)
{


alert(itemList.length);

document.write(" ")
for (i = 0;i < itemList.length;i++)
{
document.write(" " + itemList[i] + "\n")
}
document.write(" \n")
}
the php code



$a[0]=11;
$a[1]=22;
$a[2]=33;

echo "input type=\"button\" value=\"Add\" onclick=\"listItems($a);\" />";


can you help me with that?

Posted [4/05/2006 03:28:00 PM]  

Anonymous Anonymous wrote:

the echo part should be echo "<

thanks

Posted [4/05/2006 03:30:00 PM]  

Blogger Keith wrote:

JIM said...
Hi, I have problem with pass php array to javascript function.

You may be better off asking that question at a PHP message board such as the ones at phpbuilder.com or sitepoint.com

Or better yet, how about a thread at p2p.wrox.com that addresses php and javascript.

Posted [4/05/2006 08:41:00 PM]  

Anonymous Anonymous wrote:

ok, thank you very very much, I solve the problem.

the link you give me is very helpful.

Posted [4/05/2006 11:35:00 PM]  

Anonymous Anonymous wrote:

Hi, Thank you for a great tutorial on dynamically adding/deleting table rows. I have copied both the code presented on the page and the source from the page and I can't get the validate submit to work when there is data in the field. I get the popup but with an error - page not found. Thank you for any direction you can provide.

Posted [4/12/2006 07:03:00 PM]  

Blogger Keith wrote:

Anonymous said...
I get the popup but with an error - page not found.

The form submit in my example calls another page that's up at mredkj.com - tableaddrow_nw.html - so if you want the example working in your test environment, you'd need that page also.

Also, in case there's some misunderstanding, the point of the tableaddrow_nw.html page isn't to be the validation popup. It displays the form elements that were submitted, so if you have validation on, and it's opening that new window, then it passed validation.

Posted [4/12/2006 07:17:00 PM]  

Anonymous Anonymous wrote:

Keith,
Thank you. I understand that the point of the tableaddrow_nw.html page isn't to be the validation popup. I'm new to javascripting and just wanted to understand what I was missing and it was right there in front of me as part of the form.

Posted [4/13/2006 01:43:00 AM]  

Anonymous Anonymous wrote:

Hi!
I have really appreciated your tutorial.
Is someway your addRow method extensible to have a textarea in a row cell?

Posted [4/13/2006 09:44:00 AM]  

Blogger Keith wrote:

Anonymous wrote:
Is someway your addRow method extensible to have a textarea in a row cell?

Should be possible. What have you tried so far?

Posted [4/13/2006 09:56:00 AM]  

Blogger Keith wrote:

Try this:
var el = document.createElement('textarea');
el.rows = 1;
el.cols = 30;

Posted [4/14/2006 06:41:00 PM]  

Anonymous Anonymous wrote:

Everything works great and thanks for your example. I do have one question. I have two input fields and I want the to calculate a third input field. I have tried several different ways to do this, but no luck.

Here is my code:

// Script Provided by mredkj.com Last updated 2006-02-21
function addRowToTable()
{
var tbl = document.getElementById('tblProducts');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

// select cell
var cellRightSel = row.insertCell(0);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('Choose Product', '');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);

// left cell
var cellLeft = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'ProductQTY' + iteration;
el.id = 'ProductQTY' + iteration;
el.size = 2;

cellLeft.appendChild(el);

// right cell
var cellRight = row.insertCell(2);
var el = document.createElement('input');
el.type = 'text';
el.name = 'ProductPrice' + iteration;
el.id = 'ProductPrice' + iteration;
el.value = '';
el.size = 5;
el.readOnly = true;


cellRight.appendChild(el);

// Totals cell
var cellRight = row.insertCell(3);
var el = document.createElement('input');
el.type = 'text';
el.name = 'ProductTotal' + iteration;
el.id = 'ProductTotal' + iteration;
el.size = 5;
el.onchange = getTotal2;

cellRight.appendChild(el);
}

function getTotal2(frm) {
var tbl = document.getElementById('tblProducts');
var lastRow = tbl.rows.length -1;
var i;
for (i=1; 1<=lastRow; i++) {
var QTY = 100;
var Cost = 1000;
/*var QTY = document.getElementById('ProductQTY' +i).value;
var Cost = document.getElementById('ProductTotal' +i).value;*/
document.getElementById('ProductPrice' +i).value = Cost / QTY;
}
}

I commented out the two lines that set the QTY and Cost rows and set them to static values.

The error I get is:

'document.getElementByID(...)' is null or not an object.

Any help would be appreciated.

Thanks.

Posted [5/17/2006 10:43:00 AM]  

Blogger Keith wrote:

There are a few things you might want to do to clean up that code, but the one thing causing your problem is:
for (i=1; 1<=lastRow; i++) {

Change that to:
for (i=1; i<=lastRow; i++) {

You have a "1" where an "i" should be, which tells the loop to continue until 1 is less than or equal to lastRow, which would put it in an infinite loop, but luckily the browser (at least Firefox) stops execution once you start referring to a row that doesn't exist.

Posted [5/17/2006 09:11:00 PM]  

Anonymous Anonymous wrote:

Kieth,

I could just about kiss you. I won't though cause I'm married. It always helps to have a second set of eyes look at my code.

Thanks again.

Posted [5/18/2006 10:44:00 AM]  

Anonymous Anonymous wrote:

hello keith!!
your code very interesting!!

i have prob in how to get value for select type.

i` give u sample code:

var cellRight1 = row.insertCell(2);
var el1 = document.createElement('select');
el1.name = 'JENIS' + iteration;

el1.options[0] = new Option('VARCHAR2', 'VARCHAR');
el1.options[1] = new Option('NUMBER', 'NUMBER');
el1.options[2] = new Option('DATE', 'DATE');
cellRight1.appendChild(el1);


....this code to pull out the value..

for (i=1; i<=lastRow; i++) {
var col1 = document.getElementById('JENIS' + i).value;

i got an error with this ...i cannot take out the selected value to parse to col1 variable.

please help me..thanks

Posted [6/19/2006 02:46:00 AM]  

Blogger Keith wrote:

Anonymous said...
i have prob in how to get value for select type.

You need to set the id
el1.id = 'JENIS' + iteration;

Posted [6/19/2006 11:46:00 PM]  

Anonymous Anonymous wrote:

Hey guys,

I'm attempting to integrate your script into a little project I'm working on but am now stumped. A javascript / DOM guy I'm not but hope you can help me out.

I've a popup window where I'm calculating some field values which need to be passed back to input fields in a newly created row. How do I go about doing this???

Thanks in advance for your help!

David

Posted [6/20/2006 05:45:00 PM]  

Blogger Keith wrote:

David H said...
I've a popup window where I'm calculating some field values which need to be passed back to input fields in a newly created row.

Even though it's a different example, this mredkj page might help get you started: tutorial008.html

Posted [6/21/2006 02:44:00 AM]  

Blogger Ashish wrote:

Thanks for the code.. Can we index the rows where it is added? I need to create a table with each row containing a parent name with a plus sign infront of each of them. If the plus sign is clicked, we need to show all the children of that parent right below that row. The code in your blog only adds the row at the end of the table. I need to create row(s) right after the one whose plus sign is clicked. I tried to use <div> with innerHTML and I lose alignment when I do it. Help is appreciated.

Posted [6/22/2006 05:48:00 PM]  

Blogger Keith wrote:

ashish wrote...
Can we index the rows where it is added?

For starters, you might want to refer to the insert code in tabledeleterow.html

Posted [6/23/2006 03:15:00 PM]  

Anonymous Anonymous wrote:

Hello Keith,

I modified your code according to my needs.

when tried to call calculate1 function

sel.onchange = calculate1(sel.id,iteration);

i am getting errors.

this is my code..


function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);

// location cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'location' + iteration;
el.id = 'location' + iteration;
el.size = 20;

el.onkeypress = keyPressTest;
cellRight.appendChild(el);

// bank cell
var cellRight = row.insertCell(2);
var el1 = document.createElement('input');
el1.type = 'text';
el1.name = 'bank' + iteration;
el1.id = 'bank' + iteration;
el1.size = 20;

el1.onkeypress = keyPressTest;
cellRight.appendChild(el1);

// branch cell
var cellRight = row.insertCell(3);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'branch' + iteration;
el2.id = 'branch' + iteration;
el2.size = 20;

el2.onkeypress = keyPressTest;
cellRight.appendChild(el2);

// no.of flats cell
var cellRight = row.insertCell(4);
var el3 = document.createElement('input');
el3.type = 'text';
el3.name = 'noofflats' + iteration;
el3.id = 'noofflats' + iteration;
el3.size = 5;

el3.onkeypress = keyPressTest;
cellRight.appendChild(el3);

// consent cell
var cellRight = row.insertCell(5);
var el4 = document.createElement('input');
el4.type = 'text';
el4.name = 'consent' + iteration;
el4.id = 'consent' + iteration;
el4.size = 5;

el4.onkeypress = keyPressTest;
cellRight.appendChild(el4);

// tripartite cell
var cellRight = row.insertCell(6);
var el5 = document.createElement('input');
el5.type = 'text';
el5.name = 'tripartite' + iteration;
el5.id = 'tripartite' + iteration;
el5.size = 5;

el5.onkeypress = keyPressTest;
cellRight.appendChild(el5);

// select cell
var cellRightSel = row.insertCell(7);
var sel = document.createElement('select');
sel.name = 'levelofconstruction' + iteration;
sel.id = 'levelofconstruction' + iteration;
sel.onchange = calculate1(sel.id,iteration);
sel.options[0] = new Option('Select', 'Select');
sel.options[1] = new Option('Ist Stage', 'Ist Stage');
sel.options[2] = new Option('IInd Stage', 'IInd Stage');
sel.options[3] = new Option('IIIrd Stage', 'IIIrd Stage');
sel.options[4] = new Option('IVth Stage', 'IVth Stage');
cellRightSel.appendChild(sel);


// tarunits1 cell
var cellRight = row.insertCell(8);
var el6 = document.createElement('input');
el6.type = 'text';
el6.name = 'tarunits' + iteration;
el6.id = 'tarunits' + iteration;
el6.onchange = calculate1(sel.id,iteration);
el6.size = 5;

el6.onkeypress = keyPressTest;
cellRight.appendChild(el6);

// taramt1 cell
var el7 = document.createElement('input');
el7.type = 'text';
el7.name = 'taramt' + iteration;
el7.id = 'taramt' + iteration;
el7.size = 5;

el7.onkeypress = keyPressTest;
cellRight.appendChild(el7);

// actunits1 cell
var el8 = document.createElement('input');
el8.type = 'text';
el8.name = 'actunits' + iteration;
el8.id = 'actunits' + iteration;
el8.size = 5;

el8.onkeypress = keyPressTest;
cellRight.appendChild(el8);

// actamt1 cell
var el9 = document.createElement('input');
el9.type = 'text';
el9.name = 'actamt' + iteration;
el9.id = 'actamt' + iteration;
el9.size = 5;

el9.onkeypress = keyPressTest;
cellRight.appendChild(el9);

/*// taramt1 cell
var cellRight1 = row.insertCell(8);
var el7 = document.createElement('input');
el7.type = 'text';
el7.name = 'taramt' + iteration;
el7.id = 'taramt' + iteration;
el7.size = 5;

el7.onkeypress = keyPressTest;
cellRight1.appendChild(el7);

// actunits1 cell
var cellRight1 = row.insertCell(8);
var el8 = document.createElement('input');
el8.type = 'text';
el8.name = 'actunits' + iteration;
el8.id = 'actunits' + iteration;
el8.size = 5;

el8.onkeypress = keyPressTest;
cellRight1.appendChild(el8);

// actamt1 cell
var cellRight1 = row.insertCell(8);
var el9 = document.createElement('input');
el9.type = 'text';
el9.name = 'actamt' + iteration;
el9.id = 'actamt' + iteration;
el9.size = 5;

el9.onkeypress = keyPressTest;
cellRight1.appendChild(el9);
*/

// remarks cell
var cellRight1 = row.insertCell(9);
var el10 = document.createElement('input');
el10.type = 'text';
el10.name = 'remarks' + iteration;
el10.id = 'remarks' + iteration;
el10.size = 5;

el10.onkeypress = keyPressTest;
cellRight1.appendChild(el10);


}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
//if (validateChkb.checked) {
if (true) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRowNewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');

// set the target to the blank window
frm.target = 'TableAddRowNewWindow';

// submit
frm.submit();
}
function validateRow(frm)
{
//var chkb = document.getElementById('chkValidate');
//if (chkb.checked) {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length - 1;
var i;
for (i=1; i<=lastRow; i++) {
var aRow = document.getElementById('location' + i);
var bRow = document.getElementById('bank' + i);
var cRow = document.getElementById('branch' + i);
var dRow = document.getElementById('noofflats' + i);
var eRow = document.getElementById('consent' + i);
var fRow = document.getElementById('tripartite' + i);
var gRow = document.getElementById('levelofconstruction' + i);
var hRow = document.getElementById('tarunits' + i);
var iRow = document.getElementById('taramt' + i);
var jRow = document.getElementById('actunits' + i);
var kRow = document.getElementById('actamt' + i);
var lRow = document.getElementById('remarks' + i);

if (aRow.value.length <= 0) {
alert('Location ' + i + ' is empty');
document.getElementById('location' + i).focus();
return;
}
if (bRow.value.length <= 0) {
alert('Bank ' + i + ' is empty');
document.getElementById('bank' + i).focus();
return;
}
if (cRow.value.length <= 0) {
alert('Branch ' + i + ' is empty');
document.getElementById('branch' + i).focus();
return;
}
if (dRow.value.length <= 0) {
alert('No. of Flats ' + i + ' is empty');
document.getElementById('noofflats' + i).focus();
return;
}
if (eRow.value.length <= 0) {
alert('Consent Given' + i + ' is empty');
document.getElementById('consent' + i).focus();
return;
}
if (fRow.value.length <= 0) {
alert('Tripartite ' + i + ' is empty');
document.getElementById('tripartite' + i).focus();
return;
}
if (gRow.value == "Select") {
alert('Level of Construction ' + i + ' is empty');
document.getElementById('levelofconstruction' + i).focus();
//gRow.onChange(calculate1(gRow));
return;
}
if (hRow.value.length <= 0) {
alert('Target No. of Units ' + i + ' is empty');
document.getElementById('tarunits' + i).focus();
//hRow.onChange(calculate1(gRow));
return;
}
if (iRow.value.length <= 0) {
alert('Target Amount ' + i + ' is empty');
document.getElementById('taramt' + i).focus();
return;
}
if (jRow.value.length <= 0) {
alert('Actual No. of Units ' + i + ' is empty');
document.getElementById('actunits' + i).focus();
return;
}
if (kRow.value.length <= 0) {
alert('Actual No. of Units ' + i + ' is empty');
document.getElementById('actamt' + i).focus();
return;
}
if (lRow.value.length <= 0) {
alert('Remarks ' + i + ' is empty');
document.getElementById('remarks' + i).focus();
return;
}
}
//}
//openInNewWindow(frm);
alert("Success");
}
function calculate()
{

var temp = document.getElementById('levelofconstruction1');
alert("Calculate");
if(temp.value == "Ist Stage")
{
document.getElementById('taramt1').value = (document.getElementById('tarunits1').value * (74250 * 25/100));
}
else
if(temp.value == "IInd Stage")
{
document.getElementById('taramt1').value = (document.getElementById('tarunits1').value * (74250 * 50/100));
}
else
if(temp.value == "IIIrd Stage")
{
document.getElementById('taramt1').value = (document.getElementById('tarunits1').value * (74250 * 75/100));
}
else
if(temp.value == "IVth Stage")
{
document.getElementById('taramt1').value = (document.getElementById('tarunits1').value * 74250);
}
}
function calculate1(a,i)
{
var temp = a;
alert("Calculate1");

if(a.value == "Ist Stage")
{
document.getElementById('taramt'+i).value = (document.getElementById('tarunits'+i).value * (74250 * 25/100));
}
else
if(a.value == "IInd Stage")
{
document.getElementById('taramt'+i).value = (document.getElementById('tarunits'+i).value * (74250 * 50/100));
}
else
if(a.value == "IIIrd Stage")
{
document.getElementById('taramt'+i).value = (document.getElementById('tarunits'+i).value * (74250 * 75/100));
}
else
if(a.value == "IVth Stage")
{
document.getElementById('taramt'+i).value = (document.getElementById('tarunits'+i).value * 74250);
}
}

help me out..

thanks and regards...

Brahma

Posted [7/10/2006 07:17:00 AM]  

Blogger Keith wrote:

Brahma,

Try this inner function.

sel.onchange = function() {
calculate1(document.getElementById(sel.id), iteration);
}

Posted [7/12/2006 02:54:00 AM]  

Anonymous Anonymous wrote:

Hello Keith,

Thank you very much.

It works fine..

thanks and regards,

Brahma

Posted [7/12/2006 03:09:00 AM]  

Anonymous Anonymous wrote:

This code has been a great help, but I have a question.

I am retrieving values from a db in asp and creating anywhere between two and four tables/forms depending on the data. When I want to dynamically add the rows how would I determine which table/form gets the new row and input?

I tried using a counter and storing it in a hidden input field for each form/table created, but when I retrieve that value in javascript it only returns the initial value of the counter. What should I be doing?

Hope this question makes sense

Posted [7/12/2006 10:02:00 AM]  

Blogger Keith wrote:

DRoc wrote...
I am retrieving values from a db in asp and creating anywhere between two and four tables/forms depending on the data. When I want to dynamically add the rows how would I determine which table/form gets the new row and input?

You could change the function to take the table name as a parameter. If you need to differentiate the id and name values then add the table name into the names and ids.

Posted [7/13/2006 10:11:00 PM]  

Anonymous Anonymous wrote:

I'm trying to use the Table Add Row functionality with a PHP backend. I'm not very familiar with Javascript and was wondering how I could modify it to update the value of one hidden field each time a new row is added so that my PHP script knows how many text fields it has to parse into variables from the $_POST as they will be deposited into a database. Or is there some other solution to this short of a PHP loop to find all the set fields?

Posted [7/19/2006 02:58:00 AM]  

Blogger Keith wrote:

Anonymous wrote...
I'm trying to use the Table Add Row functionality with a PHP backend.

I added an example of what you're asking in a new page:
tablebasics5.html

Posted [7/21/2006 10:56:00 PM]  

Anonymous Anonymous wrote:

I was wondering how would you implement error checking on a select drop down such as your validateRow(), but used for select? I'm trying to check on users entering in something but it's not checking the 2nd row...?

Posted [7/26/2006 09:46:00 AM]  

Anonymous Anonymous wrote:

Hi Keith,

Thanks for the Table add row tutorial - has fixed some of my problems.
I have a table that has texts, selects, a calendar (within a text box) and some images that act as links. They are supposed to delete, copy, cancel changes and accept changes. Unfortunately they don't work even if I am cloning the row.
I've tried using innerHTML to put the tag together but it doesn't work. Couldn't post the code, got the "your HTML cannot be accepted" message.
Do you have any ideas? I appreciate any help.

Thank you.
Babi

Posted [8/02/2006 09:39:00 PM]  

Blogger Keith wrote:

anonymous wrote:
I was wondering how would you implement error checking on a select drop down such as your validateRow(), but used for select? I'm trying to check on users entering in something but it's not checking the 2nd row...?

Not sure what you're asking. If you took the validateRow code and modified it to check a select box, it should check all rows, because that's how the original version works on text boxes. If you're asking what you need to check to validate a select box, then you should probably look at what the selectedIndex value is.

Babi wrote:
Unfortunately they don't work even if I am cloning the row.
I've tried using innerHTML to put the tag together but it doesn't work.


When you try to clone a row do you call it like cloneNode(true). Passing in true will make sure all the content of the row is cloned. Of course, there may be some things that don't clone well and for which innerHTML won't work, so in that case you'll have to use a DOM approach (like my Table Add Row example).

If you haven't been to my comparison of innerHTML vs. DOM vs. cloneNode, check it out here: tablebasics3.html

Posted [8/02/2006 10:48:00 PM]  

Anonymous Anonymous wrote:

Hi Keith,

Thanks for your quick reply.
I checked out all the tutorials and searched the site for anything close.
Cloning the image only works [using the cloneNode(true)], but the link doesn't.
If I use the DOM approach what type of element am I supposed to create? "image" or "a"?
The other question is, how do I add the pseudo class so clicking on the image calls one of the functions?
Thanks a lot in advance.

Babi

Posted [8/02/2006 11:23:00 PM]  

Blogger Keith wrote:

Babi wrote:

If I use the DOM approach what type of element am I supposed to create? "image" or "a"?
The other question is, how do I add the pseudo class so clicking on the image calls one of the functions?


Refer to an example I posted to another one of my blog posts here. It shows how to add "a" and "image" elements and also calls a javascript function onclick.

Posted [8/03/2006 12:49:00 AM]  

Anonymous Anonymous wrote:

You are a star, Keith! Thanks heaps.

Babi

Posted [8/03/2006 07:41:00 AM]  

Anonymous Anonymous wrote:

Hi Keith,

One more questions, please.
When I clone a row, how can I get the values of the selects copied, too?
All the values of text boxes get copied, but the selects are on 'initial value'.

Thank you in advance.

Babi

Posted [8/03/2006 05:15:00 PM]  

Anonymous Anonymous wrote:

Hi Keith,

Another one.
I am trying to copy the selected row and append it to the end of the table. I have used the same method as with the delete, but it only appends a new row to the table, doesn't really clone, although the items are cloned in the function.
What is the simplest way get the row index of the current row when the icon is clicked?
Thanks in advance, again.

Babi

Posted [8/03/2006 09:39:00 PM]  

Blogger Keith wrote:

Babi,
There are different ways of keeping track of row references. I went through a few ideas while coming up with my Table Delete Row tutorial. The page doesn't have much explanation but look at the code, specifically function deleteCurrentRow which navigates the DOM to get the row index. Keep in mind I'm using a table section, so your exact code may be different.

Posted [8/04/2006 02:23:00 AM]  

Anonymous Anonymous wrote:

Thanks heaps, Keith.

I did look at it and was hoping there was an easier way; something like the onclick event detects the rownumber in which the element being clicked is, then clones the whole row and appends it to the table.

I'll try to work out something.

Thanks heaps, you've helped a lot.

Babi

Posted [8/06/2006 06:23:00 PM]  

Anonymous Anonymous wrote:

Hi I'd like to know how can I provide colspan for the cell, which is added dynamially by scripting as follows.

......
var rowOne=tb.insertRow(0)
var c11=rowOne.insertCell(0)
var c12=rowOne.insertCell(1)
......
var rowTwo=tb.insertRow(1)
........?
var c2=rowTwo.insertCell(0)
........?

Here I want to make the second row cell as a colspan of 2. When I am trying to do
...c2.colspan=2
It is not working like.... Can you any body suggest me a way to do so...... Thanking you in advance...

by seenu

Posted [8/21/2006 08:25:00 AM]  

Blogger Keith wrote:

Anonymous wrote
When I am trying to do ...c2.colspan=2
It is not working like


Try capitalizing the S
c2.colSpan=2

I tried an example using colSpan and it worked.

Posted [8/24/2006 10:34:00 AM]  

Anonymous Anonymous wrote:

Hi Keith

Im stuck up with the below prob

I have a table enclosed within div tags(div has a id)
The table has no id .TD has no id, TR has no id.

Is there anyway to read contents of whole table using JS ?


PS: i cannot add a "id" to the table.

Please respond.

Posted [8/28/2006 06:34:00 AM]  

Blogger Keith wrote:

anonymous wrote:
Is there anyway to read contents of whole table using JS ?

Here's one way that'll save the row and column coordinates along with the innerHTML to a string. innerHTML is only useful for text in the cells. If you have form elements, you'll need to have a little more complicated code.

var tbl = document.getElementById('tblSample');
var output = '';
for (var r=0; r<tbl.rows.length; r++) {
for (var c=0; c<tbl.rows[r].cells.length; c++) {
output += r + ',' + c + '=' + tbl.rows[r].cells[c].innerHTML + '\n';
}

Posted [9/01/2006 12:00:00 AM]  

Anonymous Anonymous wrote:

Excellent source of information.
I also, came to know about cloneNode here.

I have a <select></select> within one cell. I cant have an id associated with it (since Im creating this select using PHP) but the name is selName[].
I want to clone the 1st select

I would like to do something like this:

var tbl = document.getElementById("tbl");
tbl.rows[0].cells[4].select[0].cloneNode(true);

Is there a way ?

Thanks

Posted [9/10/2006 05:17:00 AM]  

Anonymous Anonymous wrote:

Should've checked before posting.
getElementsByTagName was what I was looking for.

tbl.rows[0].cells[4].getElementsByTagName("select")[0].cloneNode(true);

Posted [9/10/2006 07:15:00 AM]  

Anonymous Anonymous wrote:

Hi

Im constructing a table dynamically by retrieving data from database.

I need to apply pagination on the resultset using JS.
Max 25 records can be displayed in a page.

Also i have a sorting combo option, based on the column selected
I need to sort the whole result set and not a page level sorting.

Any help on pagination and sorting result set?

Thanks
Hope22

Posted [9/15/2006 12:29:00 AM]  

Blogger Keith wrote:

Hope22,
What you're asking is beyond the scope of this tutorial. Sorry I couldn't be of more assistance.

Posted [9/19/2006 10:01:00 AM]  

Anonymous Anonymous wrote:

Keith:

cool tutorial!

is it possible to insert into a dynamic element JavaScript that passes a variable to the funtion?

i.e. i have a SELECT with an onchange. the onchange determines which other SELECTs appear. at the end of each row is an "Add Another Row" button that creates another instance of the initial SELECT. i've got the new row to appear, and have added the onchange via newSelect.onchange = functionName;, but i cant get the onchange to pass variables to the function...

thanks,
Atg

Posted [10/17/2006 12:30:00 PM]  

Blogger Keith wrote:

Anonymous wrote...
is it possible to insert into a dynamic element JavaScript that passes a variable to the funtion?

Refer to this page:
mredkj Table Delete Row - calendar

Specifically this line:
btnCal.onclick = function () {toggleCalendar(txtInp);};

Posted [10/17/2006 09:12:00 PM]  

Anonymous Anonymous wrote:

Question on dynamicallty adding a row to the table. After i add rows and enter text in them if hit the REFRESH button in the browser the entire rows get removed. is there anyway that once a row is added with the ADD button, the row is not allowed to remove till the REMOVE button is clicked???
And also the REMOVE button always removes the last row. Can the REMOVE any row inbetween??? I need to post the data to the server side.

Posted [10/19/2006 12:32:00 PM]  

Blogger Keith wrote:

Anonymous wrote...
is there anyway that once a row is added with the ADD button, the row is not allowed to remove till the REMOVE button is clicked???
And also the REMOVE button always removes the last row. Can the REMOVE any row inbetween??? I need to post the data to the server side.


Refreshing the browser is beyond the control of simply javascript, so you'll need to save state server side or to cookies if you want values to persist after a refresh.

To delete rows other than the last row, refer to the mredkj Table Delete Row page.

Posted [10/25/2006 08:29:00 PM]