Thursday, June 21, 2007

 

Adding Rows Dynamically

I'm sure that every joe, bob, frank and jimmy already knows this but I'm not one of those guys so I figured I'd throw this out there for other relative newcomers to DHTML and Javascript.

So, if you're creating a table, it goes something like this:
<table>
<tbody>
<tr>
<td> Something here </td>
<td> Something else here</td>
</tr>
</tbody>
</table>
Right? (note: tbody seems to be required for this by ie)
So, if you want to add a row to this, all dynamic-like, the first thing to do is add an ID to the tbody (since that's the element you'll actually be adding to)
<tbody id="tbody">

Then you can add a control to your page to add the row. Something like
<input type="button" value="Add Row" />

So, aside from the rest of the page declaration (<html><head>...etc) that's all the html that you need.

What you need next is Javascript.
In the button tag, you'll add an onclick handler like this:

<input type="button" value="Add Row" onclick="addRow()" />

Then you need the javascript. Something like this:

<script type="text/javascript">
function addRow()
{
var tbody = document.getElementById("tbody");
var newRow = document.createElement("tr");
var newCell1 = document.createElement("td");
var newCell2 = document.createElement("td");
newCell1.innerHTML = "Something more";
newCell2.innerHTML = "Something else more";
newRow.appendChild(newCell1);
newRow.appendChild(newCell2);
tbody.appendChild(newRow);
}
</script>
Every time you click the Add Row button, it will add a row to the table. Of course, you can extend this to include adding dynamic data or adding different elements to different parent elements (maybe adding a button when some condition is met... i dunno - I used it to add a row to a table - what you want to use it for is your own deal).

Here's the code from top to bottom:

<html>
<head>
</head>
<body>

<script type="text/javascript">
function addRow()
{
var tbody = document.getElementById("tbody");
var newRow = document.createElement("tr");
var newCell1 = document.createElement("td");
var newCell2 = document.createElement("td");
newCell1.innerHTML = "Something more";
newCell2.innerHTML = "Something else more";
newRow.appendChild(newCell1);
newRow.appendChild(newCell2);
tbody.appendChild(newRow);
}
</script>
<table>
<tbody id="tbody">
<tr>
<td> Something here </td>
<td> Something else here</td>
</tr>
</tbody>
</table>
<input type="button" value="Add Row" onclick="addRow()" />
</body>
</html>

A couple of things:
1) don't forget to add an ID to the element you want to add to.
2) don't forget the second 'a' in javascript. That one's a bugger.

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?