Click to See Complete Forum and Search --> : Using javascript to create table rows containing form elements


liquilife
04-26-2005, 12:25 AM
Good morning/afternoon/evening everyone,

I am really struggling with a little bit of javascript I am working on. I know the solution with a bit of javascript is simple but unfortunately I am no javascript wizard.

I have a form that will initially contain 1 table row with 3 form elements (2 text boxes and one dropdown select). The form tags are wrapped around the table. What I want to do is use a form button to add new rows on demand. So if the button (labeled with a +) was clicked a new row would be added with the same 3 form elements listed above but with a new name for the element (1,2,3 so on..). Each time the + was clicked a new row would appear. I know this is probably simple but just can't seem to find any examples anywhere on this entire world wide web. If you can help me, please I would be so greatful.

You can view an example page of what the form will look like at http://www.rainbowphotography1.com/formtest.htm . It has no functionality at this time.

Thank you to ANYONE who can point me in the right direction or if you could whip up a quick little bit of javascript for me. It is more then I deserve but I'm asking anyways. :)

Kor
04-26-2005, 06:18 AM
try this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[0].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>

liquilife
04-26-2005, 08:36 AM
Kor,

Wow, you do not know how appreciative I am of your help! That is absolutely perfect for what I needed. Perfect! Thank you so very, very, very much for taking the time to assist me. :)

Robbie

Grubolsch
04-26-2005, 09:06 AM
I used the bases of this script to, was looking for someting like that for almost 3 days. Thank you Kor.

Kor
04-26-2005, 09:47 AM
You're welcome...

It is nothing special than the "almighty" :p DOM methods... :D Particulary the cloneNode() method...

outka5t
05-06-2005, 11:23 AM
Hi I have tried to add the js to a form of my own below

<form action="test.php" method="post">

<table width="766" border="0" cellspacing="0" cellpadding="5">
<tr>
<td width="98"><select name="amount">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select></td>
<td width="191"><input type="text" name="desc" /></td>
<td width="191"><input type="text" name="exvat" /></td>
<td width="191"><input type="text" name="vat" /></td>
<td width="191"><input type="text" name="total" /></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table>


If I add a row and fil it in then hit submit (i added a form action to go to a simple out put page
foreach ($HTTP_POST_VARS as $key => $value)
{
echo "$key, $value<br>";
}

echo "<br><br>";
as above)

I find that the first row of the previous form is outputted fine but the second row is not. The second row does not output the correct information and the variables are not fully renamed.

Any help much appreciated

Kor
05-06-2005, 12:04 PM
yes, there was a mistake. Try this (remove the shownamefunction and the button afterwards)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="submit" type="submit" value="Submit" />
<br>
<br>
<input name="button" type="button" onclick="shownames()" value="Show names">
</form>
</body>
</html>

outka5t
05-06-2005, 12:14 PM
nice one... cheers

shmunaz
05-14-2005, 04:40 AM
How if i want to put the header in the table.

Kor
05-16-2005, 03:23 AM
If you use <thead> to do that, it does not matter, as the table structure will be
<table>
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>

In my code, the root inside which the rows are referenced is always the tbody

var root = r.parentNode;//the root (tbody)

tdob
01-15-2008, 03:24 PM
Wow, this is a great example. Im sorry to bump a 2 or 3 year old thread but it has helped me a lot.

I have a question or two, is there anyway to add the new row without copying the actual values of the elements? For example, clone the elements themselves, but not the value that is in the elements?

Kor
01-15-2008, 03:41 PM
You may clone them anytime before the user will give them values, if you mean the form's input elements... Need an example?

tdob
01-15-2008, 03:45 PM
I suppose what I ultimately looking for is this:

The user inputs the values on my form (I have department, account, description, total, etc..)

Then if the users wants to input a second row, they click the add row button and a seond row come up but it doesnt contain whatever the user entered for the first row, the inputs are blank?

I have the form working, just when they add a row it always by default contains what the user inputted in the row above.

Also, one last thing, which is no big deal, but is there a way to only display the add row button on the last row, as opposed to every row?

I know all of this defeats the purpose of "clone" but just figured I would ask.

Kor
01-15-2008, 03:56 PM
It is to be done. I've send you a PM (Private Message). I can give you an example tomorrow, here, my time, if it is not too late

tdob
01-15-2008, 03:59 PM
yes thats fine, thanks for your help! :)

codingisfun
01-16-2008, 12:14 AM
KOR, could you post the new code here please? I would appreciate that. Good work! By the way, I really liked java.

Thanks.

Kor
01-16-2008, 04:42 AM
A basic example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneRow(){
var rows=document.getElementById('mytab').getElementsByTagName('tr');
var index=rows.length;
clone=rows[index-1].cloneNode(true);
var inputs=clone.getElementsByTagName('input'), inp, i=0 ;
while(inp=inputs[i++]){
inp.name=inp.name.replace(/\d/g,'')+(index+1);
}
}
function addRow(){
var tbo=document.getElementById('mytab').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}
onload=cloneRow;
</script>
</head>
<body>
<form>
<table id="mytab">
<tr>
<td>Foo <input type="text" name="foo_1"></td>
<td>Fee <input type="text" name="fee_1"></td>
</tr>
</table>
<br>
<input type="button" value="Add a new row" onclick="addRow()">
</form>
</body>
</html>

tdob
01-16-2008, 10:41 AM
Thank you, this seems to work.

Would adding some javascript that automatically makes a new input appear if a user types in the "foo" field mess up this? Would it be hard to do?

tdob
01-16-2008, 01:42 PM
i have a question about this. does it have to be in a table? right now it is triggered on 'tr' I see. What if I dont want the form in a table, is there anyway to define it otherwise?

Kor
01-17-2008, 02:48 AM
If not a table, than probably in a div... It would not be much difference...

tdob
01-17-2008, 09:56 AM
If not a table, than probably in a div... It would not be much difference...

I tried doing a div before but nothing seems to happens? I was replacing the 'tr' with 'div'?

Kor
01-17-2008, 10:07 AM
may I see your HTML? (or a significant part of it)

tdob
01-17-2008, 01:58 PM
Here is what I have...


<html>
<head>
<title>Submit An Expense Request</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneRow(){
var rows=document.getElementById('mytab').getElementsByTagName('tr');
var index=rows.length;
clone=rows[index-1].cloneNode(true);
var inputs=clone.getElementsByTagName('input'), inp, i=0 ;
while(inp=inputs[i++]){
inp.name=inp.name.replace(/\d/g,'')+(index+1); }
}
function addRow(){
var tbo=document.getElementById('mytab').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}
onload=cloneRow;
</script>


</head>
<body>
<form id="mytab" action="?link=summary.php" method="post">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<input type="hidden" name="id[]" />
<select name="department[]">
<option selected>Department</option><option>Administration</option><option>Customer Service</option><option>Executive</option><option>Finance</option><option>I.T.</option><option>Marketing</option><option>Materials Management</option><option>Product Development</option><option>Selling</option> </select>

<select name="account[]">
<option selected>Account</option><option>ADMIN CHARGES FOR LATE DELIVERIES & SHORTAGES</option><option>AUDIT FEES</option><option>BAD DEBT EXPENSE</option><option>BANK CHARGES</option><option>BANK PENALTY & INTEREST</option><option>CELLUAR PHONE</option><option>CONSULTANT SERVICES</option><option>CONVENTIONS/TRADE SHOWS</option><option>COPIER CHARGES</option><option>COURIER</option><option>CREDIT BUREAU CHARGES</option><option>DONATIONS</option><option>EDP COMMUNICATION</option><option>EDUCATION</option><option>EMPLOYEE UNIFORMS</option><option>FAX</option><option>FAX CHARGES</option><option>FOREIGN X - REALIZED</option><option>FORWARDING & DOC'N CHRG</option><option>HARDWARE EXPENSES</option><option>INTEREST INCOME</option><option>LEGAL FEES</option><option>LUNCH ROOM</option><option>MAIL ROOM</option><option>MEALS & ENTER. SALES</option><option>MEALS & ENTERTAINMENT</option><option>MEETINGS</option><option>MEMBERSHIPS & DUES</option><option>NUTRITIONAL ANALYSIS - R&D</option><option>OUTSIDE CONTRACTS</option><option>PENSION CONSULTING</option><option>PRODUCT TEST TRIALS - R&D</option><option>R&M BUILDING</option><option>R&M BUILDING (GENERAL)</option><option>R&M EDP HARDWARE</option><option>R&M EDP SOFTWARE</option><option>RECRUITING</option><option>RENT</option><option>SANITATION/CLEANING</option><option>SOFTWARE EXPENSE</option><option>SPECIAL EVENTS</option><option>SUBSCRIPTIONS</option><option>SUPPLIES - OFFICE</option><option>SUPPLIES - QUALITY SERVICE</option><option>SUPPLIES - R&D</option><option>SUPPLIES - SHIPPING</option><option>TELEPHONE</option><option>TEMPORARY HELP</option><option>TRAVEL</option><option>VEHICLES/MILEAGE/RENTALS</option> </select>

<br><br>Description (if required)<input type="text" name="description[]" value=" " />
Amount<input type="text" name="amount[]" size="4" />
GST<input type="text" name="gst[]" value="0" size="4" />
PST<input type="text" name="pst[]" value="0" size="4" />
Other Tax<input type="text" name="other_tax[]" value="0" size="4" />
<br><br>Total<input type="text" name="total[]" size="4" />
Currency<select name="currency[]"><option>CDN</option><option>USD</option></select>
Receipt<select name="receipt[]"><option>YES</option><option>NO</option></select>
</tr>
</table><br />
<input name="button" type="button" value="Insert another expense" onclick="addRow(this.parentNode.parentNode)">
<button type="submit" name="submit" value="submit" />Submit</button>
</form>
</body>
</html>


I tried adding a <div> instead of using <table> and <tr>, and replace 'tr' with 'div' in the javascript, but didnt seem to work. As you can see right now I just have everything inside one <tr>, if I added another <tr> it would break the clone.

tdob
01-17-2008, 02:29 PM
Also, something else I have been trying to figure is validation. I want to ensure my selection lists (account and description) are not set to the default value.

I have found samples on the internet, however I need to give the java the field name, but as you see the name here is always dynamic, it could be description[0] or description[5] etc... How would i incorporate validation into this?

Once again, im forever greatful for your help.

Kor
01-18-2008, 03:06 AM
Here you are the DIV variant:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv
</script>
</head>
<body>
<form id="myForm" action="?link=summary.php" method="post">
<div id="myDiv">
<div>
<input type="hidden" name="id[]" />
<select name="department[]">
<option selected>Department</option><option>Administration</option><option>Customer Service</option><option>Executive</option><option>Finance</option><option>I.T.</option><option>Marketing</option><option>Materials Management</option><option>Product Development</option><option>Selling</option> </select>

<select name="account[]">
<option selected>Account</option><option>ADMIN CHARGES FOR LATE DELIVERIES & SHORTAGES</option><option>AUDIT FEES</option><option>BAD DEBT EXPENSE</option><option>BANK CHARGES</option><option>BANK PENALTY & INTEREST</option><option>CELLUAR PHONE</option><option>CONSULTANT SERVICES</option><option>CONVENTIONS/TRADE SHOWS</option><option>COPIER CHARGES</option><option>COURIER</option><option>CREDIT BUREAU CHARGES</option><option>DONATIONS</option><option>EDP COMMUNICATION</option><option>EDUCATION</option><option>EMPLOYEE UNIFORMS</option><option>FAX</option><option>FAX CHARGES</option><option>FOREIGN X - REALIZED</option><option>FORWARDING & DOC'N CHRG</option><option>HARDWARE EXPENSES</option><option>INTEREST INCOME</option><option>LEGAL FEES</option><option>LUNCH ROOM</option><option>MAIL ROOM</option><option>MEALS & ENTER. SALES</option><option>MEALS & ENTERTAINMENT</option><option>MEETINGS</option><option>MEMBERSHIPS & DUES</option><option>NUTRITIONAL ANALYSIS - R&D</option><option>OUTSIDE CONTRACTS</option><option>PENSION CONSULTING</option><option>PRODUCT TEST TRIALS - R&D</option><option>R&M BUILDING</option><option>R&M BUILDING (GENERAL)</option><option>R&M EDP HARDWARE</option><option>R&M EDP SOFTWARE</option><option>RECRUITING</option><option>RENT</option><option>SANITATION/CLEANING</option><option>SOFTWARE EXPENSE</option><option>SPECIAL EVENTS</option><option>SUBSCRIPTIONS</option><option>SUPPLIES - OFFICE</option><option>SUPPLIES - QUALITY SERVICE</option><option>SUPPLIES - R&D</option><option>SUPPLIES - SHIPPING</option><option>TELEPHONE</option><option>TEMPORARY HELP</option><option>TRAVEL</option><option>VEHICLES/MILEAGE/RENTALS</option> </select>

<br><br>Description (if required)<input type="text" name="description[]" value=" " />
Amount<input type="text" name="amount[]" size="4" />
GST<input type="text" name="gst[]" value="0" size="4" />
PST<input type="text" name="pst[]" value="0" size="4" />
Other Tax<input type="text" name="other_tax[]" value="0" size="4" />
<br><br>Total<input type="text" name="total[]" size="4" />
Currency<select name="currency[]"><option>CDN</option><option>USD</option></select>
Receipt<select name="receipt[]"><option>YES</option><option>NO</option></select>
</div>
</div>
<input name="button" type="button" value="Insert another expense" onclick="addDiv()">
<button type="submit" name="submit" value="submit" />Submit</button>
</form>
</body>
</html>

tdob
01-18-2008, 09:28 AM
Thank you very much. Java is really useful, wish I knew more.. you want to sell your brain :)

I also have the following code for trying to validate some fields:

<script type='text/javascript'>
function madeSelection(elem, helperMsg){
if(elem.value == "Department"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
</script>


Then I would have to use a
<input type='button'
onclick="madeSelection(document.getElementById('department'), 'Please Choose Something')"
value='Submit' />


My problem is, using my example you helped me with above, my element is never going to be department. It would be department[0] or department[1], however I have no clue how to incorporate this into the Java?

Kor
01-18-2008, 10:00 AM
id and name are different things. Don't mix or confound them.

Your correspondent elements will have all the same name, say "department[]". It is up to your server-side code (the CGI where your form is subimtted) to treat them as an array. For instance php applications can do that.

The validation is a separate thing. Usually it has to be done on using the onsubmit event, with a return call, placed within the form element.

A basic example could be as:


function madeSelection(f){
var sel=f['deparment[]'], i=0, s;
while(s=sel[i++]){
if(s.value == 'Department'){
alert('Please Choose Something');
s.focus();
return false;
}
}
}

and the handler:

<form onsubmit="return madeSelection(this)">
....
....
<input type="submit" name="Sub" value="Submit">
</form>

====

Java is really useful

Note: Javascript is NOT Java

tdob
01-18-2008, 01:45 PM
Thanks again, however this in combination with the form I have above, produces no result.

I will try tinkering with it, but I am not getting a prompt when it is still on 'Department' and im not getting any javascript errors either.

tdob
01-21-2008, 02:01 PM
I hate to bug you, but the verification does not work for me, nothing seems to happen.

Kor
01-22-2008, 02:55 AM
You should give values to your options. Anyway, you need that by all means, in order to submit something to the CGI.

<select name="department[]">
<option selected value="Department">Department</option>
<option value="Administration">Administration</option>
<option value="Customer Service">Customer Service</option>
...
</select>

tdob
01-22-2008, 12:21 PM
Thanks for the reply, I did try that, but still no luck. Feel like ive been staring at the same code forever, this is the part of the form:


<script type="text/javascript">
function madeSelection(f){
var sel=f['deparment[]'], i=0, s;
while(s=sel[i++]){
if(s.value == 'Department'){
alert('Please Choose Something');
s.focus();
return false;
}
}
}
</script>


</head>
<body>
<form id="form-expense" action="?link=summary.php" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tr align="center">
<td>Department</td>
<td>Account</td>
<td>Description</td>
</tr>
<tr aligin="center">
<td align="center">
<input type="hidden" name="id[]" />
<select name="department[]">
<option selected value=Department>Department</option>
<option value=Administration>Administration</option>
<option value=Customer Service>Customer Service</option>
<option value=Executive>Executive</option>
<option value=Finance>Finance</option>
<option value=I.T.>I.T.</option>
<option value=Marketing>Marketing</option>
<option value=Materials Management>Materials Management</option>
<option value=Product Development>Product Development</option>
<option value=Selling>Selling</option>
</select></td>

Kor
01-23-2008, 02:57 AM
Typo

var sel=f['department[]'], i=0, s;


Note: it is a good habit to quote the HTML attributes' values:

...
<option selected value="Department">Department</option>
<option value="Administration">Administration</option>
<option value="Customer Service">Customer Service</option>
...

tdob
01-23-2008, 09:38 AM
Typo

var sel=f['department[]'], i=0, s;


Note: it is a good habit to quote the HTML attributes' values:

...
<option selected value="Department">Department</option>
<option value="Administration">Administration</option>
<option value="Customer Service">Customer Service</option>
...


Thank you so much, I feel stupid for not seeing a simple typo.. arggh..

Yes, I got burned with the quotations in HTML yesterday as the wrong values were getting passed, so I fixed that up.

I suppose to close this once and for all, to check other fields should I create a brand new function, or is there a way to include it in this one?

tdob
01-23-2008, 09:54 AM
Unfortunately, now it seems to prompt whenever I click the submit button, whether or not it actually equals "Department"?? However, this only happens when there is one row, if a user inserts another row or two it acts as it should.

This is going to be the death of me!

Kor
01-23-2008, 09:56 AM
You may use a single function... but, as, most of the time, a validation function is a "personalized" one, I need to know what kind of elements you need to validate and for what (empty values, lack of options' selection, numbers... and so on).

tdob
01-23-2008, 10:21 AM
You may use a single function... but, as, most of the time, a validation function is a "personalized" one, I need to know what kind of elements you need to validate and for what (empty values, lack of options' selection, numbers... and so on).

I need to validate and ensure a selection has been made from the selection boxes in department[] and account[]. The default selection is "Department" and "Account" respectively.

I also have a input box named amount[], I would like to ensure there is a numeric value in this input.

Im not sure if you saw the last message (sorry if you did) but it seems the validation doesnt work correctly if there is only 1 row. Upon clicking submit it always prompts to select a value even if you have, however if you insert other rows it works as desired?

tdob
01-24-2008, 12:26 PM
i hate to bump my issue, but i was wondering if someone with a little more knowledge could help me out?

thanks to everyone.

Kor
01-24-2008, 02:43 PM
Is it so hard to understand the pattern of the code and try to use/modify it?... Have you tried? Can we see your trial?

No offense, but... really, we can not fulfill your whole work, can we? Should we?

tdob
01-24-2008, 03:56 PM
Yes, I have tried. I am really new to javascript but very good with PHP and MySQL, this is my first attempt to merge all 3 together. Sorry for the questions.

What I am saying right now, is the validation you helped me with doesnt work for the first set of inputs. However, if I choose to input another row of inputs, the validation works as desired. It seems as though the validation process is expecting a second row straight away.

The only other issue I had was having is adding more inputs to validate once it works. I dont need you to code it all out for me, I just need an example like you gave me that uses more than one. I have tried many different things that failed (last 2 days) but I didnt see the value in posting them.

Here is my relevant code after php has did its thing filling in values:

<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv

function madeSelection(f){
var sel=f['department[]'], i=0, s;
while(s=sel[i++]){
if(s.value == 'Department'){
alert('Please Choose Something');
s.focus();
return false; } } }
</script>


</head>
<body>
<form id="form-expense" action="?link=summary.php" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tr align="center">
<td>Department</td>
<td>Account</td>
<td>Description</td>
</tr>
<tr aligin="center">
<td align="center">
<input type="hidden" name="id[]" />
<select name="department[]">
<option selected value="Department">Department</option><option value="Administration">Administration</option><option value="Customer Service">Customer Service</option><option value="Executive">Executive</option><option value="Finance">Finance</option><option value="I.T.">I.T.</option><option value="Marketing">Marketing</option><option value="Materials Management">Materials Management</option><option value="Product Development">Product Development</option><option value="Selling">Selling</option> </select></td>

<td align="center">
<select name="account[]">
<option selected value="Account">Account</option><option value="ADMIN CHARGES FOR LATE DELIVERIES & SHORTAGES">ADMIN CHARGES FOR LATE DELIVERIES & SHORTAGES</option><option value="AUDIT FEES">AUDIT FEES</option><option value="BAD DEBT EXPENSE">BAD DEBT EXPENSE</option><option value="BANK CHARGES">BANK CHARGES</option><option value="BANK PENALTY & INTEREST">BANK PENALTY & INTEREST</option><option value="CELLUAR PHONE">CELLUAR PHONE</option><option value="CONSULTANT SERVICES">CONSULTANT SERVICES</option><option value="CONVENTIONS/TRADE SHOWS">CONVENTIONS/TRADE SHOWS</option><option value="COPIER CHARGES">COPIER CHARGES</option><option value="COURIER">COURIER</option><option value="CREDIT BUREAU CHARGES">CREDIT BUREAU CHARGES</option><option value="DONATIONS">DONATIONS</option><option value="EDP COMMUNICATION">EDP COMMUNICATION</option><option value="EDUCATION">EDUCATION</option><option value="EMPLOYEE UNIFORMS">EMPLOYEE UNIFORMS</option><option value="FAX">FAX</option><option value="FAX CHARGES">FAX CHARGES</option><option value="FOREIGN X - REALIZED">FOREIGN X - REALIZED</option><option value="FORWARDING & DOC'N CHRG">FORWARDING & DOC'N CHRG</option><option value="HARDWARE EXPENSES">HARDWARE EXPENSES</option><option value="INTEREST INCOME">INTEREST INCOME</option><option value="LEGAL FEES">LEGAL FEES</option><option value="LUNCH ROOM">LUNCH ROOM</option><option value="MAIL ROOM">MAIL ROOM</option><option value="MEALS & ENTER. SALES">MEALS & ENTER. SALES</option><option value="MEALS & ENTERTAINMENT">MEALS & ENTERTAINMENT</option><option value="MEETINGS">MEETINGS</option><option value="MEMBERSHIPS & DUES">MEMBERSHIPS & DUES</option><option value="NUTRITIONAL ANALYSIS - R&D">NUTRITIONAL ANALYSIS - R&D</option><option value="OUTSIDE CONTRACTS">OUTSIDE CONTRACTS</option><option value="PENSION CONSULTING">PENSION CONSULTING</option><option value="PRODUCT TEST TRIALS - R&D">PRODUCT TEST TRIALS - R&D</option><option value="R&M BUILDING">R&M BUILDING</option><option value="R&M BUILDING (GENERAL)">R&M BUILDING (GENERAL)</option><option value="R&M EDP HARDWARE">R&M EDP HARDWARE</option><option value="R&M EDP SOFTWARE">R&M EDP SOFTWARE</option><option value="RECRUITING">RECRUITING</option><option value="RENT">RENT</option><option value="SANITATION/CLEANING">SANITATION/CLEANING</option><option value="SOFTWARE EXPENSE">SOFTWARE EXPENSE</option><option value="SPECIAL EVENTS">SPECIAL EVENTS</option><option value="SUBSCRIPTIONS">SUBSCRIPTIONS</option><option value="SUPPLIES - OFFICE">SUPPLIES - OFFICE</option><option value="SUPPLIES - QUALITY SERVICE">SUPPLIES - QUALITY SERVICE</option><option value="SUPPLIES - R&D">SUPPLIES - R&D</option><option value="SUPPLIES - SHIPPING">SUPPLIES - SHIPPING</option><option value="TELEPHONE">TELEPHONE</option><option value="TEMPORARY HELP">TEMPORARY HELP</option><option value="TRAVEL">TRAVEL</option><option value="VEHICLES/MILEAGE/RENTALS">VEHICLES/MILEAGE/RENTALS</option> </select></td>

<td align="center"><input type="text" name="description[]" size="30" value=" " /></td>
</tr>
<tr><td colspan="3">&nbsp;</td></tr>
</table>
<table border="1" cellpadding="0" cellspacing="0" width="80%">
<tr align="center">
<td>Amount</td>
<td>GST</td>
<td>PST</td>
<td>Other Tax</td>
<td>Total</td>
<td>Currency</td>
<td>Receipt</td>
</tr>
<tr align="center">
<td><input type="text" name="amount[]" size="4" /></td>
<td><input type="text" name="gst[]" value="0" size="4" /></td>
<td><input type="text" name="pst[]" value="0" size="4" /></td>
<td><input type="text" name="other_tax[]" value="0" size="4" /></td>
<td><input type="text" name="total[]" value="?" readonly size="4" /></td>
<td><select name="currency[]"><option>CDN</option><option>USD</option></select></td>
<td><select name="receipt[]"><option>YES</option><option>NO</option></select></td>
</tr>
</table>
</div>
</div>
<br><br>
<p align="center"><input name="button" type="button" value="Insert another expense" onclick="addDiv()">
<input name="submit" type="submit" value="Submit">
</form>
</body>


I have tried messing with the javascript but im unable to get it to work. Perhaps I should just scrap it as im not familiar with it and dont wont to keep bothering you guys.

Kor
01-25-2008, 04:03 AM
function madeSelection(){
var names=['department[]','account[]'], n, sel, s, i, j=0;
while(n=names[j++]){
sel=document.getElementsByName(n); i=0;
while(s=sel[i++]){
if(s.selectedIndex==0){alert('Please Choose Something');s.focus();return false;}
}
}
}


<form id="form-expense" action="?link=summary.php" method="post" onsubmit="return madeSelection()">

tdob
01-25-2008, 09:27 AM
I would just like to say thank you very much, you have really shown me some creative ways to do things, i have read up on some of these things and hopefully this can be a good starting point for me.

thanks again, im sorry if I was a bit persistent, hate it when I cant get something to work.

do you know a good book (or heck, have you written) one that specializes in javascript working with webforms, etc..?

Kor
01-25-2008, 10:05 AM
You are welcome...:)
Regarding the books, no, I don't know books specialized in javascript working with webforms...

Everything I know, I know from some "classical" sites of standards as:
http://www.w3.org/
http://www.ecma-international.org/publications/standards/Ecma-367.htm

some good tutorials:

http://www.w3schools.com/
http://www.quirksmode.org/
http://www.howtocreate.co.uk/

... and, of course, from Web Forums like this one :)

rajnath
07-12-2008, 10:05 AM
Hi the example is working fine. But only one problem.

I want the options list as
<option value="item1" >item1</option>
<option value="item2">item2</option>
<option value="item3" selected="selected">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

"item 3 " shouldbe selected. But i tried n number way , always it is showint the selected item as "item1" (i.e. the one that present in the first option).

Can you please help me.

Kor
07-13-2008, 02:10 PM
And your whole code is?

tdob
07-20-2008, 05:28 PM
You are welcome...:)
Regarding the books, no, I don't know books specialized in javascript working with webforms...

Everything I know, I know from some "classical" sites of standards as:
http://www.w3.org/
http://www.ecma-international.org/publications/standards/Ecma-367.htm

some good tutorials:

http://www.w3schools.com/
http://www.quirksmode.org/
http://www.howtocreate.co.uk/

... and, of course, from Web Forums like this one :)

Hi Kor,

Ive been using this code and I have the need for something that seems so simple but yet so hard. I need to keep track of (and display) the number of the current row.

For example, when a user clicks to insert another row of elements, I would like to be able to display that it is Row 2, or Row 3. I have been unable to find a way to do this and display it in PHP, im thinking it is not possible?

Kor
07-21-2008, 03:29 AM
Post the new aspect of your code, please.

tdob
07-21-2008, 09:58 AM
Post the new aspect of your code, please.

Hi Kor, not much has changed code wise. Here is what I have.


<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
<?php $count+=1; ?>
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv

function madeSelection(){
var names=['team[]','profile[]'], n, sel, s, i, j=0;
while(n=names[j++]){
sel=document.getElementsByName(n); i=0;
while(s=sel[i++]){
if(s.selectedIndex==0){alert('Please Choose Something');s.focus();return false;}
}
}
}
</script>

</head>
<body>
<form id="form-expense" action="<?php $_SERVER['PHP_SELF']?>" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0">
<tr align="center">
<td>Pick #</td>
<td>Team</td>
<td>Player</td>
<td>Pick info (Optional, how team acquired pick, etc...)</td>
</tr>
<tr aligin="center">
<td><?php echo $count; ?></td>
<input type="hidden" name="id[]" />
<td align="center"><select name="team[]">
<?php
echo '<option selected value="Team">Team Name</option>';
echo $optionteams;
?>
</select></td>
<td align="center">
<select name="player[]">
<?php
echo '<option selected value="Player">Player</option>';
echo $optionprofiles;
?>
</select></td>
<p align="center"><input name="button" type="button" value="Insert another selection" onclick="addDiv()">
<input name="submit" type="submit" value="Submit">


Where I have Pick# I would like to somehow display the current rows number. So if it is the first row it would display 1, if a user inserts another selection through the addDiv() function it would be pick #2, and so on... I dont know of a way I can track how many rows have been added and at the same time output it via PHP?

Kor
07-21-2008, 10:21 AM
The HTML is incomplete (tags are not close, etc...) Something is missing. It is important to see the complete HTML code.

tdob
07-21-2008, 10:26 AM
The HTML is incomplete (tags are not close, etc...) Something is missing. It is important to see the complete HTML code.

Well it is integrated with PHP. I will post the entire page, I thought only the above would be relevant, sorry. I am not sure what im looking for is possible, as the PHP is server side. I would just like a way to output the current row number and increment it when a users adds another row of elements. I have tried with PHP to no success.


<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
<?php $count+=1; ?>
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv

function madeSelection(){
var names=['team[]','profile[]'], n, sel, s, i, j=0;
while(n=names[j++]){
sel=document.getElementsByName(n); i=0;
while(s=sel[i++]){
if(s.selectedIndex==0){alert('Please Choose Something');s.focus();return false;}
}
}
}
</script>

<?php
include('connect.php');
global $user;
$userid = $user->uid;

$getteams = @mysql_query("SELECT * FROM teams order by name ASC");
if (!$getteams) { exit('<p>Error performing query: ' . mysql_error() . '</p>'); }

while ($rowgetteams = mysql_fetch_array($getteams)) {
$optionteams .= '<option value="' .$rowgetteams['id']. '">' .$rowgetteams['name']. '</option>'; }

$getprofiles = @mysql_query("SELECT * FROM profiles order by name ASC");
if (!$getprofiles) { exit('<p>Error performing query: ' . mysql_error() . '</p>'); }

while ($rowgetprofiles = mysql_fetch_array($getprofiles)) {
$optionprofiles .= '<option value="' .$rowgetprofiles['id']. '">' .$rowgetprofiles['name']. '</option>'; }
?>

</head>
<body>
<form id="form-expense" action="<?php $_SERVER['PHP_SELF']?>" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0">
<tr align="center">
<td>Pick #</td>
<td>Team</td>
<td>Player</td>
<td>Pick info (Optional, how team acquired pick, etc...)</td>
</tr>
<tr aligin="center">
<td><?php echo $count; ?></td>
<input type="hidden" name="id[]" />
<td align="center"><select name="team[]">
<?php
echo '<option selected value="Team">Team Name</option>';
echo $optionteams;
?>
</select></td>
<td align="center">
<select name="player[]">
<?php
echo '<option selected value="Player">Player</option>';
echo $optionprofiles;
?>
</select></td>

<td><textarea cols="50" rows="5" name="pick_info[]" /></textarea></td>
</tr>
<tr><td colspan="4">Reasoning behind pick<br><textarea cols="90" rows="10" name="description[]" /></textarea></td></tr>
</table>
</div>
</div>
<br><br>
<p align="center"><input name="button" type="button" value="Insert another selection" onclick="addDiv()">
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>

<?php
if (isset($_POST['submit'])) {

//Import into database
$sql = 'INSERT INTO table SET';
$sql .= ' user = \'' . $userid. '\'';

mysql_query("SET autocommit = 0") or die (mysql_error());
mysql_query("START TRANSACTION") or die (mysql_error());
mysql_query("BEGIN") or die (mysql_error());
mysql_query($sql) or die (mysql_error());
$getmockid = mysql_insert_id();

foreach ($_POST['id'] as $key => $value)
{
$pick_number=$key+1;
$id = $_POST['id'][$key];
$player = $_POST['player'][$key];
$team = $_POST['team'][$key];
$description = nl2br($_POST['description'][$key]);
if ($_POST['pick_info'][$key]) {
$pickinfo=nl2br($_POST['pick_info'][$key]); }

//Import into database
$sql2 = 'INSERT INTO table_detail SET';
$sql2 .= ' player_id = \'' . $player . '\'';
$sql2 .= ', team_id = \'' . $team . '\'';
$sql2 .= ', mock_id = \'' . $getmockid . '\'';
$sql2 .= ', pick_number = \'' . $pick_number . '\'';
$sql2 .= ', comments = \'' . $description . '\'';
if ($pickinfo) { $sql2 .= ', pick_info = \'' . $pick_info . '\''; }

// mysql_query($sql2) or die(mysql_error());
if(!mysql_query($sql2)) {
echo '<p>Error performing query: ' . mysql_error() . '</p>';
mysql_query("ROLLBACK"); die; }
else { mysql_query("COMMIT"); echo "RECORDS ADDED!!!"; }


}
}

Kor
07-21-2008, 10:29 AM
Would be ok to send, on submit, the number of rows as a hidden input's value?

tdob
07-21-2008, 10:39 AM
Would be ok to send, on submit, the number of rows as a hidden input's value?

Yes any way to get it would be fine, I would also need to be able to output the value to page though.

Kor
07-21-2008, 11:06 AM
javascript can not interfere with php, at least not the way you tried. Is this what you want?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
var nr=root.getElementsByTagName('table').length+1;
clone.getElementsByTagName('td')[4].firstChild.nodeValue=nr;
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv

function madeSelection(){
var names=['team[]','profile[]'], n, sel, s, i, j=0;
while(n=names[j++]){
sel=document.getElementsByName(n); i=0;
while(s=sel[i++]){
if(s.selectedIndex==0){alert('Please Choose Something');s.focus();return false;}
}
}
}
</script>
</head>
<body>
<form id="form-expense" action="<?php $_SERVER['PHP_SELF']?>" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0">
<tr align="center">
<td>Pick #</td>
<td>Team</td>
<td>Player</td>
<td>Pick info (Optional, how team acquired pick, etc...)</td>
</tr>
<tr aligin="center">
<td>1</td>
<input type="hidden" name="id[]" />
<td align="center"><select name="team[]">
<?php
echo '<option selected value="Team">Team Name</option>';
echo $optionteams;
?>
</select></td>
<td align="center">
<select name="player[]">
<?php
echo '<option selected value="Player">Player</option>';
echo $optionprofiles;
?>
</select></td>

<td><textarea cols="50" rows="5" name="pick_info[]" /></textarea></td>
</tr>
<tr><td colspan="4">Reasoning behind pick<br><textarea cols="90" rows="10" name="description[]" /></textarea></td></tr>
</table>
</div>
</div>
<br><br>
<p align="center"><input name="button" type="button" value="Insert another selection" onclick="addDiv()">
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>

tdob
07-21-2008, 11:27 AM
javascript can not interfere with php, at least not the way you tried. Is this what you want?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneDiv(){
var divs=document.getElementById('myDiv').getElementsByTagName('div');
clone=divs[divs.length-1].cloneNode(true);
}
function addDiv(){
var root=document.getElementById('myDiv');
var divs=root.getElementsByTagName('div');
var nr=root.getElementsByTagName('table').length+1;
clone.getElementsByTagName('td')[4].firstChild.nodeValue=nr;
root.appendChild(clone);
clone=divs[divs.length-1].cloneNode(true);
}
onload=cloneDiv

function madeSelection(){
var names=['team[]','profile[]'], n, sel, s, i, j=0;
while(n=names[j++]){
sel=document.getElementsByName(n); i=0;
while(s=sel[i++]){
if(s.selectedIndex==0){alert('Please Choose Something');s.focus();return false;}
}
}
}
</script>
</head>
<body>
<form id="form-expense" action="<?php $_SERVER['PHP_SELF']?>" method="post" onsubmit="return madeSelection(this)">
<div id="myDiv">
<div>
<br>
<table border="1" cellpadding="0" cellspacing="0">
<tr align="center">
<td>Pick #</td>
<td>Team</td>
<td>Player</td>
<td>Pick info (Optional, how team acquired pick, etc...)</td>
</tr>
<tr aligin="center">
<td>1</td>
<input type="hidden" name="id[]" />
<td align="center"><select name="team[]">
<?php
echo '<option selected value="Team">Team Name</option>';
echo $optionteams;
?>
</select></td>
<td align="center">
<select name="player[]">
<?php
echo '<option selected value="Player">Player</option>';
echo $optionprofiles;
?>
</select></td>

<td><textarea cols="50" rows="5" name="pick_info[]" /></textarea></td>
</tr>
<tr><td colspan="4">Reasoning behind pick<br><textarea cols="90" rows="10" name="description[]" /></textarea></td></tr>
</table>
</div>
</div>
<br><br>
<p align="center"><input name="button" type="button" value="Insert another selection" onclick="addDiv()">
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>


Wow, yes it is exactly what I want. I knew the PHP portion wasnt going to work, and messed around with some java but nothing close to what you did!

It works great, but how exactly are you picking up the value in the javascript? I see your working with the Table, then somehow you get the proper <td>? What does the [4] represent? Sorry for the questions just fascinated..

tdob
07-21-2008, 11:59 AM
The 4 is the 4th <td> starting at 0. However, what in the code makes the value auto increment?

Kor
07-21-2008, 12:40 PM
The 4 is the 4th <td> starting at 0. However, what in the code makes the value auto increment?
Each time when you append the clone, you add a new TABLE element. I have simply counted the tables each time and have added 1:

var nr=root.getElementsByTagName('table').length+1;

I could have also counted the DIV elements of the root

seba4
10-06-2008, 09:45 AM
Hi

i have read that posts, and found your code really interesting, for adding rows.

I have added it into my code, but i got one problem.
What i am trying to do, is that i want a calculation, and a possibility to add more calculation.

The HTML code looks like that:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">




<html>
<head><link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250">
<title>Izračun</title>
<link rel="stylesheet" type="text/css" href="izracun.css" />
<SCRIPT language="JavaScript" SRC="izracun2.js"></SCRIPT>
<SCRIPT language="JavaScript" SRC="izracun.js"></SCRIPT>


</head>
<body>
<div id="glava"><script type="text/javascript">myFunction ()</script>
<!-- Meni- gumbi-->

<div id="sb_content"><br><br>
<h3>Informativni izračun</h3>





<form name="foto" method="post">
<table>
<tr class="table_row">
<td width="50px" class="labelcell_prvi"><label for="state">Izdelki:</label></td>
<td class="fieldcell">
<select name="vrsta[stevilka]" onchange="Kvadratura();">
<option value="0">- - - - - - Izberi - - - - - - -</option>
<option value="1">Fototapeta</option>
<option value="2">Fototapeta Stucco</option>
<option value="3">Grafika za steklo</option>
<option value="4">Slikarsko platno</option>
<option value="5">Samolepilna grafika</option>
</select>
</td> <td class="space"> </td>
<td class="labelcell_prvi"><label for="name">Količina:</label></td>
<td class="labelcell"><input class="mere" value="1" type="text" name="kolicina[stevilka]" onblur="Kvadratura()"/> kom</td>
<td class="space"> </td>
<td class="labelcell_prvi"><label for="name">Širina:</label></td>
<td class="labelcell"><input class="mere" type="text" name="sirina[stevilka]" onblur="Kvadratura()"/> cm</td>
<td class="space"> </td>
<td class="labelcell_prvi"><label for="address1">Višina:</label></td>
<td class="labelcell"><input class="mere" type="text" name="visina[stevilka]" onBlur="Kvadratura();"/> cm</td>
<td class="space"> </td>
<td class="labelcell_prvi"><label for="address1">Kvadratura:</label></td>
<td class="labelcell"><input class="fieldcell2" type="text" name="kvadratura[stevilka]" size="8"/> m2</td>
<td class="space"> </td>
<td class="labelcell_prvi"><label for="address1"></label></td>
<td class="labelcell" colspan="2"><label for="address1">+ 25,00 € Priprava za tisk</label></td>
<td class="space"> </td>
<td class="labelcell_prvi"><label for="address1">Izračun:</label></td>
<td class="labelcell"><input class="fieldcell3" type="text" name="znesek[stevilka]" size="8"/> €</TD>

<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>


</table>
</form>
<p class="dogodki"><br><br><br>
<b>Legenda:</b>
<br><br>
<b>Fototapete</b> <br>
Tiskane na poseben papir, ki se lepi na gladke stene(omet, knauf, iverica) na enak način in z lepilom kot navadne tapete.
Papir dopušča čiščenje z mehko vlažno krpo brez agresivnih čistil. Fototapete niso primerne za neporozne površine: iveral. steklo ipd. in za zunanjo uporabo.<br>
Obstoj tapet v notranjih prostorih je preko 20 let.Odsvetujemo uporabo v vlažnih prostorih.<br><br><br>

<b>Fototapete - Stucco</b> <br>
Tiskane so na poseben strukturiran papir, ki daje bogatejši videz kot običajni papir.
Na zid se, prav tako kot običajno lepijo z lepilom za tepete. <br>
Priporočamo lepilo za težke tapete.
Posamezni trakovi se lepijo brez prekrivanj - na stik<br><br><br>

<b>Grafika za steklo</b> <br>
Najboljša rešitev za vlažne prostore in kjer je potrebno pogostejše čiščenje: kuhinje, kopalnice ipd..
Grafika je tiskana na posebno folijo, ki omogoča lepljenje na hrbtno stran stekla.<br>
Obstojnost je preko 25 let in v tem je največja prednost pred direktnim tiskom na steklo.
Poleg tega omogoča popolnoma neprosojno izvedbo, kar je zelo pomembno pri lepljenju s silikoni.
Možne so tudi različno prosojne in obojestransko vidne izvedbe za vrata ali pregradne stene.<br><br><br>

<b>Slikarsko platno</b> <br>
Fotopovečave na slikarsko platno dajejo poseben, bogatejši vtis zaradi strukture materiala. Platno je naeto na podokvir tako, da potiskani del pokriva tudi vse zunanje robove.
Uporabne so za dekoracije prostorov kot samostojne slike na steni.<br>
So tudi zelo primerno in lepo darilo.<br><br><br>

<b>Samolepilna grafika</b> <br>
Tiskana na samolepilno folijo, ki se lepi na vse neporozne ravne površine (omare, PVC plošče ipd.) na katerih ni možna oz. priporočljiva uporaba fototapet.
Za površine, ki so bolj izpostavljene dotikom ipd.(omare, vrata, ...), priporočamo dodatno zaščitno plastifikacijo.<br>
Obstojnost: Zunaj cca 5 let, v prostorih preko 20 let.<br><br><br>
</p>




</body><!--end of body-->
</html>




The javascript code for calculation i was using before adding rows.

function Kvadratura()
{

foto.kvadratura.value = foto.sirina.value * foto.visina.value / 10000;
if (foto.vrsta.value == 1)
{
if (foto.kvadratura.value < 3)
{foto.znesek.value = (( 32 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if ((foto.kvadratura.value >= 3) && (foto.kvadratura.value < 12))
{foto.znesek.value = (( 28 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if ((foto.kvadratura.value >= 12) && (foto.kvadratura.value < 30))
{foto.znesek.value = (( 25 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if (foto.kvadratura.value >= 30)
{foto.znesek.value = (( 22 * foto.kvadratura.value) * foto.kolicina.value) + 25;}
}
else if (foto.vrsta.value == 2)
{
if (foto.kvadratura.value < 3)
{foto.znesek.value = (( 39 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if ((foto.kvadratura.value >= 3) && (foto.kvadratura.value < 12))
{foto.znesek.value = (( 35 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if ((foto.kvadratura.value >= 12) && (foto.kvadratura.value < 30))
{foto.znesek.value = (( 32 * foto.kvadratura.value) * foto.kolicina.value) + 25;}

if (foto.kvadratura.value >= 30)
{foto.znesek.value = (( 29 * foto.kvadratura.value) * foto.kolicina.value) + 25;}
}
else if (foto.vrsta.value == 3) {foto.znesek.value = (( 96 * foto.kvadratura.value) * foto.kolicina.value) + 25;}
else if (foto.vrsta.value == 4) {foto.znesek.value = (( 120 * foto.kvadratura.value) * foto.kolicina.value) + 25;}
else if (foto.vrsta.value == 5) {foto.znesek.value = ((54.5 * foto.kvadratura.value) * foto.kolicina.value) + 25;}


}



And your code:


function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}



I am trying to connect that 2 codes, so if i add one line than the calculation will calculate second line appart too. I have tried but it just calculates first line, and stops at second line or any line that is next.

taziz
12-09-2008, 12:21 PM
I can't get this working in IE7 but it works fine in other browsers. Is this a bug with IE7??

taziz
12-09-2008, 12:23 PM
Here is my function..

function addRow(r){
var root = document.getElementById('tblViewFeed');//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[1].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}

Kor
12-10-2008, 06:10 AM
What is document.getElementById('tblViewFeed') ? A TABLE or a TBODY element?

redskin
12-22-2008, 03:56 AM
Hi,
i have almost the some script but different problem.
a friend of me has made a script for me (now he is on holiday for 3 weeks)
i wonder if someone can help or assist me how to make it the way i want.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Request form</title>
<link href="main.css" type="text/css" rel="stylesheet">
</head>

<script>
function add_formrow(){
if (!this.table_formcontainer)
this.table_formcontainer = document.getElementById("table_formcontainer");

if (!this.table_formcontainer)
return;

var new_row = table_formcontainer.insertRow(-1);
var new_cell1 = new_row.insertCell(0);
var new_cell2 = new_row.insertCell(1);
var new_cell3 = new_row.insertCell(2);

var new_input1 = document.createElement("input");
new_input1.type = "text";
new_cell1.appendChild(new_input1);

var new_input2 = document.createElement("input");
new_input2.type = "text";
new_cell2.appendChild(new_input2);

var new_input3 = document.createElement("select");
new_input3.name="transport[]";
var options = ["No", "Bike", "Car", "Motorcycle", "Public transport"];
for (var i = 0; i < options.length; i++)
{
var option = document.createElement("option");
option.value = options[i];
option.text= options[i];
try
{
new_input3.add(option, null);
}
catch(error)
{
new_input3.add(option);
}
}
new_cell3.appendChild(new_input3);
}
</script>

<body>
<div id="credit"><b>T e s t</b></div>
<br>
<form method="post" action="" name="data">
<fieldset> <legend>
<font color="blue"><b>Request form</b></font></legend><br>
<table id="table_formcontainer">
<tr>
<td width="10">Name</td> <td>Age<td>Transport<td>&nbsp;</td> </td>
</tr>

</table>
<table>
<tr>
<td width="500" align="right">[ b<a href="#" onclick='add_formrow();'>+</a> ]</td>
</tr>
<tr>
<td width="10"><br><input type="submit" name="submit" value=" S e n d "> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td></td>
</tr>
</table>
</form></fieldset>


<br>
</body>
</html>
Question:
1. how to make one extra button to deleterow()
2. how to send it with php

thanks in advance

tamoshniy123
07-09-2009, 03:54 AM
THanks for the code, KOR, you are amazing. Been searching internets for a while, and this is the best [and the only good one] so far. Many thanks!

sleeper24
08-09-2009, 08:01 PM
Kor,

I've seen the code you have for a form, however that was only for a row.

I have this simple form, and inside of that form I have a table with multiple rows and columns. The user enters and selects information they need to. Once done if they need another table, they can click on add and it will add another table inside of that form. If they click on delete it would remove the last table inserted.

How can I use your JS code to implement this? Any help is greatly appreciated.

My form code:
<form name="gj" id="gj" method="post" action="">
<table id="nogap">
<tbody>
<tr id="headrow">
<th><b><u> Date </u></b></th>
<th></th>
<th><b><u> Account </u></b></th>
<th></th>
<th><b><u> Credit </u></b></th>
<th></th>
<th><b><u> Debit </u></b></th>
</tr>
<tr>
<td>
<input type="text" size="8" maxlength="10">
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td>
<select name="options" onClick="">
<option value="empty">
<option value="Cash">Cash
<option value="Accounts Receivable">Accounts Receivable
<option value="Inventory">Inventory
<option value="PPE">Property, Plant, & Equipment
<option value="Accounts Payable">Accounts Payable
</select>
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> $ <input type="text" size="10" maxlength=15> </td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> </td>
</tr>
<tr class="oddline">
<td>&nbsp;</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<select name="options" onClick="">
<option value="empty">
<option value="Cash">Cash
<option value="Accounts Receivable">Accounts Receivable
<option value="Inventory">Inventory
<option value="PPE">Property, Plant, & Equipment
<option value="Accounts Payable">Accounts Payable
</select>
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> </td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> $ <input type="text" size="10" maxlength="15"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> ( <input type="text" size="31" maxlength="45"> ) </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><hr></td> <td><hr></td> <td><hr></td> <td><hr></td> <td><hr></td>
<td><hr></td> <td><hr></td>
</tr>
</tbody>
</table>
<div id = addon1>
<input name="add" type="button" value="Add Acct" onclick="" />
<input name="remove" type="button" value="Remove Acct" onclick="" />
<input name="post" type="button" value="Post to GL" onclick="" />
</div>
</form>

sleeper24
08-09-2009, 09:20 PM
Kor,

I solve the adding portion but when click add for the first time, it throws the original table off alignment. Everything table you insert after that is align correctly beneath the first one added.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneRow(){
var rows = document.getElementById('nogap').getElementsByTagName('tbody');
var index = rows.length;
clone = rows[index - 1].cloneNode(true);
var inputs = clone.getElementsByTagName('input'), inp, i = 0;

while (inp = inputs[i++]) {
inp.name = inp.name.replace(/\d/g, '') + (index + 1);
}
}

function addRow(){
var tbo = document.getElementById('nogap').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}

onload = cloneRow;
</script>
</head>
<body>
<div id="accttransaction">
<form name="gj" id="gj" method="post" action="">
<table id="nogap">
<tbody>
<tr id="headrow">
<th><b><u> Date </u></b></th>
<th></th>
<th><b><u> Account </u></b></th>
<th></th>
<th><b><u> Credit </u></b></th>
<th></th>
<th><b><u> Debit </u></b></th>
</tr>
<tr>
<td>
<input type="text" size="8" maxlength="10">
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td>
<select name="options" onClick="">
<option value="empty">
<option value="Cash">Cash
<option value="Accounts Receivable">Accounts Receivable
<option value="Inventory">Inventory
<option value="PPE">Property, Plant, & Equipment
<option value="Accounts Payable">Accounts Payable
</select>
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> $ <input type="text" size="10" maxlength=15> </td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> </td>
</tr>
<tr class="oddline">
<td>&nbsp;</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<select name="options" onClick="">
<option value="empty">
<option value="Cash">Cash
<option value="Accounts Receivable">Accounts Receivable
<option value="Inventory">Inventory
<option value="PPE">Property, Plant, & Equipment
<option value="Accounts Payable">Accounts Payable
</select>
</td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> </td>
<td> &nbsp;&nbsp;&nbsp;&nbsp; </td>
<td> $ <input type="text" size="10" maxlength="15"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> ( <input type="text" size="31" maxlength="45"> ) </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td><hr></td> <td><hr></td> <td><hr></td> <td><hr></td> <td><hr></td>
<td><hr></td> <td><hr></td>
</tr>
</tbody>
</table>
<!-- ############### add/remove accounts or Post to GL ################ -->
<div id = addon1>
<input name="add" type="button" value="Add Acct" onclick="addRow()" />
<input name="remove" type="button" value="Remove Acct" onclick="" />
<input name="post" type="button" value="Post to GL" onclick="" />
</div>
</form>
</div>
</body>
</html>

Kor
08-10-2009, 05:18 AM
Now, if you changed the code in order to clone a TBODY element, make sure you will append the clone to the TBODY's parent which is the TABLE element.

function addRow(){
var tab = document.getElementById('nogap');
tab.appendChild(clone);
cloneRow();
}


- remove the tr's id (<tr id="headrow">). You don't need it and it is is illegal to have more than a single element with the same id.

sleeper24
08-10-2009, 07:02 PM
Can I turn the <tr id="headrow"> to <tr class="headrow"> Because I need this row to align correctly? Thanks by the way, and do you have any pointers on how to go about deleting the row just inserted.

Kor
08-12-2009, 02:06 PM
and do you have any pointers on how to go about deleting the row just inserted.
Can you detail a little bit? You want a button, or something to delete a particular row/tbody ?

sleeper24
08-12-2009, 02:39 PM
Kor,

The code I have solved up above on adding multiple row at once that you help me correct it.

I want to delete all those rows that was added if the button delete was clicked.

paul2k1uk
01-23-2010, 04:39 PM
Hi,
Has anyone got a function to remove a added row? The examples above are perfect for me just i dont fully understand how to add a bit to remove a row thats been added.

Many thanks
Paul

paul2k1uk
02-04-2010, 04:53 PM
anyone be able to help me out with a function to remove a line thats been added?

Thanks

Kor
02-05-2010, 02:35 AM
To remove it when? On which action? From where?

paul2k1uk
02-05-2010, 04:05 AM
Thanks for the reply Kor,

I need some help to add a function to remove a row thats been added. say if a user adds a row but then would like to remove it before the form is submitted. So there would be a link on the side of every row added. im assuming this is possible but wouldnt know, very new to playing with javascript


function delRow() {

BLAH BLAH

}

dsp77
02-15-2010, 05:17 AM
Hello,

i'm in need of help with adding some rows to a table, i saw the script from Kor and is its very interesting but i'm not able to integrate with my table. Here is the table i have:
<table id="" cellspacing="1" class="tablesorter">
<thead>
<tr>
<th class="center">Nr. crt</th>
<th class="center">Denumire</th>
<th class="center">Document justificativ Denumire/ nr./ data</th>
<th class="center">UM</th>
<th class="center">Cant</th>
<th class="center">Valoare totala (lei)</th>
<th class="center">Valoare decontata din bugetul proiectului (lei)</th>
</tr>
</thead>
<tr>
<td class="center">1</td>
<td><input name="denumire1" type="text" id="denumire1" value="" /></td>
<td><input name="doc1" type="text" id="doc1" value="" /></td>
<td><input name="um1" type="text" id="um1" value="" /></td>
<td><input name="cant1" type="text" id="cant1" value="" /></td>
<td><input name="val1" type="text" id="val1" value="" /></td>
<td><input name="bug1" type="text" id="bug1" value="" /></td>
</tr>
<tr>
<td class="center">2</td>
<td><input name="denumire2" type="text" id="denumire2" value="" /></td>
<td><input name="doc2" type="text" id="doc2" value="" /></td>
<td><input name="um2" type="text" id="um2" value="" /></td>
<td><input name="cant2" type="text" id="cant2" value="" /></td>
<td><input name="val2" type="text" id="val2" value="" /></td>
<td><input name="bug2" type="text" id="bug2" value="" /></td>
</tr>
<tr>
<td colspan="5"><strong>TOTAL MATERIALE CONSUMABILE, PIESE DE SCHIMB:</strong></td>
<td width="97">&nbsp;</td>
<td width="165">&nbsp;</td>
</tr>
</table>

sudharshan1987
02-23-2010, 12:54 PM
Hai KOR & everyone
Iam a newbie to javascript. I am developing an application which involves computation based on the user input .
The design is like this : I have a html page with javascript in which tables are dynamically generated(using your clone code), whenever user wants to add another table and give input into it . I am attaching the code here .After submiting, the values are passed to a php page where computation is done based on the input values.
The problem realy starts here like how to access data individualy from javascript which are POSTED to a php page .Please I need your help .
The html page is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
function cloneRow(){
var rows=document.getElementById('mytab').getElementsByTagName('tr');
var index=rows.length;
clone=rows[index-1].cloneNode(true);
var inputs=clone.getElementsByTagName('input'), inp, i=0 ;
while(inp=inputs[i++]){
inp.name=inp.name.replace(/\d/g,'')+(index+1);
}
}
function addRow(){
var tbo=document.getElementById('mytab').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}
onload=cloneRow;
</script>
</head>
<body>
<form action="m_approach2.php" method="post">
<table id="mytab">
<tr>
<td><div align="center">sigma2</div></td>
<td><div align="center">sigma4</div></td>
<td><div align="center">sigma5</div></td>
<td><div align="center">sigma7</div></td>
<td><div align="center">sigma9</div></td>
<td><div align="center">sigma10</div></td>
</tr>
<tr>
<td>
<input name="input2[]" type="text" size="5" />//is this correct? is input2[0] = value of what user entered in the first column of the second row?
</td>
<td>
<input name="input4[]" type="text" size="5" />
</td>
<td>
<input name="input5[]" type="text" size="5" />
</td>
<td>
<input name="input7[]" type="text" size="5" />
</td>
<td>
<input name="input9[]" type="text" size="5" />
</td>
<td>
<input name="input10[]" type="text" size="5" />
</td>
</table>
<br>
<input type="button" value="Add a new row" onclick="addRow()">
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>


My php page is smthin like this
m_approach2.php is

<?php
set_time_limit(0);
$in=$_POST["input0"];//how to get all the inputed value in the variable?
$in0=$_POST["input"];
$in4=$_POST["input4"];
$in5=$_POST["input5"];
$in6=1-$in5;
$in7=$_POST["input7"];
$in3=1-$in4-$in7;
$in9=$_POST["input9"];
$in8=1-$in9;
$in10=$_POST["input10"];
$in11=1-$in10;
?>

Janthro
03-09-2010, 04:58 PM
Ok, I have an interesting twist to the code for you Kor. I need to be able to have 3 separate add row buttons on the same page that each would be pulling a different set of variables. How would I change your code to do that? I don't really know javascript, but they want me to change a paper to be online with some changes. Any ideas?

Kor
03-10-2010, 04:33 AM
The problem realy starts here like how to access data individualy from javascript which are POSTED to a php page .
You may use AJAX:
http://en.wikipedia.org/wiki/Ajax_%28programming%29
http://www.w3schools.com/Ajax/Default.Asp

Kor
03-10-2010, 04:34 AM
Ok, I have an interesting twist to the code for you Kor. I need to be able to have 3 separate add row buttons on the same page that each would be pulling a different set of variables. How would I change your code to do that? I don't really know javascript, but they want me to change a paper to be online with some changes. Any ideas?
Post what you have so far.

noob45
04-21-2010, 09:09 PM
<?php
echo "first row".$_GET[textfield_a]."<br>";
echo "second row".$_GET[textfield_a_1];

?>

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
</head>
<body>
<form action="1.php" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="submit" type="submit" value="Submit" />
<br>
<br>
<input name="button" type="button" onclick="shownames()" value="Show names">
</form>
</body>
</html>


what am i doing wrong here? i am not able to print(echo) the second textbox (textfield_a_1)...

noob45
04-21-2010, 11:55 PM
hmm i think i solved my problem..
im posting the code for other's reference.

<?php
echo count($_POST)."<br>";

$i=0;
$numberofrows = count($_POST)/2;
echo "num of rows = ".$numberofrows;
while($i<$numberofrows){
$first = "first".$i;
$second = "second".$i;

if (!empty($_POST[$first]) && !empty($_POST[$second]) ){
echo "<br>";
echo $i." ".$_POST[$first];
echo "<br>";
echo $i." ".$_POST[$second];
echo "<br>";
}
$i++;
}

?>

<html>
<head>
<title>untitled</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
var clone;
var i=1;
function cloneRow(){
var rows=document.getElementById('mySampleTable').getElementsByTagName('tr');
clone=rows[rows.length-1].cloneNode(true);
//alert(rows.length);
//var inp=clone.getElementsByTagName('input')[0];
//inp.name=inp.name.replace("txtRow0","first"+i);
//var sel=clone.getElementsByTagName('input')[1];
//sel.name=sel.name.replace("txtRow1","second"+i);

var inp=clone.getElementsByTagName('input')[0];
//alert(inp.getAttribute('name'));
inp.name=inp.name.replace(inp.getAttribute('name'),"first"+i);
var sel=clone.getElementsByTagName('input')[1];
sel.name=sel.name.replace(sel.getAttribute('name'),"second"+i);
i++;

}
function addRow(){
var tbo=document.getElementById('mySampleTable').getElementsByTagName('tbody')[0];
tbo.appendChild(clone);
cloneRow();
}
function removeRow(){
var rows=document.getElementById('mySampleTable').getElementsByTagName('tr');
if(rows[1]){
rows[0].parentNode.removeChild(rows[rows.length-1]);
}
}
onload=cloneRow

function submitform()
{
document.eval_edit.submit();
}


</script>
</head>
<body>
<form action="1.php" name="eval_edit" id=eval_edit method="post" format="html">
<table align="center" width = "75%">
<tr>
<td align = "center">
click add to you know, add a row, and remove to remove a row, and submit to submit your page! whee!
</td>
</tr>
<tr>
<td align = "center">
<!--- very imporant to give the table an id --->
<!--- otherwise it won't know where to edit --->
<table border="1" id="mySampleTable">
<tr>
<td>
Type of Leave
</td>
<td>
No. of Days allowed
</td>

</tr>
<!--- i create the initial row by hand, there are a lot of --->
<!--- different ways to do this depending on what parsing --->
<!--- language you use, i found this was easiest for the --->
<!--- snippet, but experiment, do your thing mang. --->
<!--- this matches the same specs we laid out in the javascript --->
<tr>

<td><input type="text" name="first0" size="40" >
</td>
<td>
<input type="text" name="second0" size="40" >
</td>
</tr>
</table>

<!--- our buttons call our javascript functions when clicked --->
<input type="button" value="Add" onclick="addRow();">
<input type="button" value="Remove" onclick="removeRow();">
<!--<input type="submit" value="Submit">-->
<a href="javascript: submitform()">Search</a>
</td>
</tr>
</table>
</form>

</body>
</html>

richardishere
06-21-2010, 02:05 PM
how do you include <textarea>

nebchill26
07-08-2010, 11:02 PM
hi i hope this thread is still alive i need to ask something in particular about this, i have already figured out how to use your function to add,what i need to do know is how to delete the last form elements added? hope to hear a feedback.tnx

shanehussain
03-09-2011, 03:26 AM
This is an amazing script. Helping me to create a dynamic form that can add rows for more entries. But Its bringing some issues if i use Textarea. any ideas ? as the value of textarea is NOT in the attrib but between the tags ?how to reach that ?

Kor
03-09-2011, 04:23 AM
TEXTAREA? Give it a value.

laptopalias
04-28-2011, 06:53 AM
This is a great script, and just what i was looking for - I can't believe how long this thread's been kicking around!

What if I just want the plus button to appear on the bottom row only?

Kor
04-28-2011, 07:01 AM
On which script do you refer?

laptopalias
04-28-2011, 07:10 AM
Your second one (I think)

Kor
04-28-2011, 08:19 AM
Post it here. Or post your code, where you have integrated it.

laptopalias
04-28-2011, 08:55 AM
See below; this page is going to be generated by some php so, as far as 'integrating' goes, I'm still developing that side of things...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="submit" type="submit" value="Submit" />
<br>
<br>
<input name="button" type="button" onclick="shownames()" value="Show names">
</form>
</body>
</html>

Kor
04-28-2011, 09:21 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/*<![CDATA[*/
function addRow(){
var root = document.getElementById('myTab').getElementsByTagName('tbody')[0]; //the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
/*]]>*/
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0" id="myTab">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"></td>
</tr>
</table><br />
<input name="addARow" type="button" value="Add a Row" onclick="addRow()">
<br />
<br />
<input name="submit" type="submit" value="Submit" />
<br />
<br />
<input name="button" type="button" onclick="shownames()" value="Show names">
</form>
</body>
</html>

IMPORTANT NOTE: If you are using XHTML notation (ie: <br />, <input />), be consistent and use it all over. And make sure you are using an XHTML Doctype as well. And isolate the embedded javascript code inside CDATA islands, as in my example above.

laptopalias
04-28-2011, 10:59 AM
Thanks, I'll have a play around with that. Actually, I've just spotted that my situation is a teeny bit more complicated - I'll have several similar, consecutive tables and I need to be able to add rows to any of them - but this has certainly pointed me in the right direction. Thanks.

Kor
04-28-2011, 11:06 AM
You may pass the id of each table to the function as an argument.

function addRow(tabid){
var root = document.getElementById(tabid).getElementsByTagName('tbody')[0]; //the root
...
onclick="addRow('mytab1')
...
onclick="addRow('mytab2')
...

laptopalias
04-28-2011, 12:00 PM
Like this? Firebug's giving me an error:

document.getElementById(tabid) is null
var root = document.getElementById(tab...ntsByTagName('tbody')[0]; //the root

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/*<![CDATA[*/
function addRow(tabid){
var root = document.getElementById(tabid).getElementsByTagName('tbody')[0]; //the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
var cSel = cRow.getElementsByTagName('select')[0];
cSel.setAttribute('name',cSel.getAttribute('name')+'_'+(allRows.length+1));//change the selecet's name
root.appendChild(cRow);//appends the cloned row as a new row
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
/*]]>*/
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0" id="myTab">
<tr>
<td width="191"><input type="text" name="textfield_a" /></td>
<td width="191"><input type="text" name="textfield_b" /></td>

<td width="98"><select name="select">
<option value="item1" selected="selected">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
<option value="item4">item4</option>
<option value="item5">item5</option>

</select></td>
<td width="286"></td>
</tr>
</table><br />
<input name="addARow" type="button" value="Add a Row" onclick="addRow('mytab1')">
<br />
<br />
<input name="submit" type="submit" value="Submit" />
<br />
<br />
<input name="button" type="button" onclick="shownames()" value="Show names">
</form>
</body>
</html>

laptopalias
04-29-2011, 08:14 PM
OK, this is much more along the lines of what I was after; hope it helps someone else...

<form>
<table id = 1>
<thead>

<tr>

<th>Mon 25/04/11</th>

<th>Project</th>

<th>Description</th>

</tr>

</thead>

<tbody>
<tr><td></td>

<td><select>

<option>project 1</option>

<option>project 2</option>

<option>project 3</option>

<option>project 4</option>

<option>project 5</option>

</select></td>

<td><input type = 'text'/></td>

</tr>

</tbody>
</table>
<p>
<input type='button' value='Add' onclick='addRowClone(1);' />
</p> <table id = 2>
<thead>

<tr>

<th>Tue 26/04/11</th>

<th>Project</th>

<th>Description</th>

</tr>

</thead>

<tbody>
<tr><td></td>

<td><select>
<option>project 1</option>

<option>project 2</option>

<option>project 3</option>

<option>project 4</option>

<option>project 5</option>

</select></td>

<td><input type = 'text'/></td>

</tr>

</tbody>
</table>
<p>
<input type='button' value='Add' onclick='addRowClone(2);' />
</p> <table id = 3>
<thead>

<tr>

<th>Wed 27/04/11</th>

<th>Project</th>

<th>Description</th>

</tr>

</thead>

<tbody>

<tr><td></td>

<td><select>
<option>project 1</option>

<option>project 2</option>

<option>project 3</option>

<option>project 4</option>

<option>project 5</option>

</select></td>

<td><input type = 'text'/></td>

</tr>

</tbody>
</table>
<p>
<input type='button' value='Add' onclick='addRowClone(3);' />

</p> <table id = 4>
<thead>

<tr>

<th>Thu 28/04/11</th>

<th>Project</th>

<th>Description</th>

</tr>

</thead>

<tbody>
<tr><td></td>

<td><select>
<option>project 1</option>

<option>project 2</option>

<option>project 3</option>

<option>project 4</option>

<option>project 5</option>

</select></td>

<td><input type = 'text'/></td>

</tr>

</tbody>
</table>
<p>
<input type='button' value='Add' onclick='addRowClone(4);' />
</p> <table id = 5>
<thead>

<tr>

<th>Fri 29/04/11</th>

<th>Project</th>

<th>Description</th>

</tr>

</thead>

<tbody>
<tr><td></td>

<td><select>
<option>project 1</option>

<option>project 2</option>

<option>project 3</option>

<option>project 4</option>

<option>project 5</option>

</select></td>

<td><input type = 'text'/></td>

</tr>

</tbody>
</table>

<p>
<input type='button' value='Add' onclick='addRowClone(5);' />
</p> </form>

<script>
function addRowClone(tblId)
{
var tblBody = document.getElementById(tblId).tBodies[0];
var newNode = tblBody.rows[0].cloneNode(true);
tblBody.appendChild(newNode);
}
</script>