Forum Moderators: open

Message Too Old, No Replies

Adding dynamic input rows to a form?

         

bhays

3:03 am on May 16, 2005 (gmt 0)

10+ Year Member



I've got a big form, in which one part contains a varied number of contacts. I would like to be able to add and remove a row of input fields for the contacts with a link.


<form>
<table>
<tr><td>Name</td><td>Phone</td><td>Email</td><td></td></tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td>Add Row</td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
<td>Delete Row</td>
</tr>
</table>
</form>

I've tried using some of the DOM stuff with addRow, but I can't get the dynamic rows into the table...

Thanks

ajkimoto

3:37 pm on May 16, 2005 (gmt 0)

10+ Year Member



bhays,

How about something like this:

<script type="text/javascript">
<!--
//this function accepts the id of the table to which
//you want to add a row
function addRows(cid){

//here we point the tbody variable to the table
var tbody = document.getElementById(cid).getElementsByTagName("TBODY")[0];

//here we create a row element
var row = document.createElement("TR");

//here we create the first cell element
var t1 = document.createElement("TD");

//here we popuate the first cell with 'Test1'
t1.innerHTML='Test1'

//here we create the second cell element
var t2 = document.createElement("TD");

//here we popuate the first cell with email@server.com'
t2.innerHTML='email@server.com'

//here we append the cells to the created row element
row.appendChild(t1)
row.appendChild(t2)

//here we append the created row element to the table
tbody.appendChild(row)

}
//-->
</script>

<style type="text/css">

</style>

</head>

<body>
<table id="myTable" border="1">
<tbody>
<tr><td>Name</td><td>Email</td></tr>
<tr><td>Andrew Stone</td><td>astone@nowhere.com</td></tr>
<tr><td>Ima Pseudonym</td><td>ap@nowhere.com</td></tr>
</tbody>
</table>
<br />

<!-- This button calls the addRows function, passes the name of the table to the function //-->
<button onclick="addRows('myTable')">Add Row</button>
</body>
</html>

Hope this helps,

ajkimoto

orion_rus

3:43 pm on May 16, 2005 (gmt 0)

10+ Year Member



The easiest way to insert new rows is following:
<table id='mytable'>
<tr>
...
</tr>
</table>
<script>
document.getElementByID('mytable').innerHTML+='<tr><td></td><td></td><td></td></tr>';
</script>

The easisest way to remove a row is just make it tr style='display:none'

you can make it like this:
<script>
table=document.getElementsByTagName('tr');
table[3].style.display='none'; // to hide 4 tr in a table
</script>
Good luck to you

Bernard Marx

8:15 pm on May 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



document.getElementByID('mytable').innerHTML+='<tr><td></td><td></td><td></td></tr>';

Hmm. Internet Explorer will not like that at all.
No messing with innerHTML inside tables.