Dynamic Tables: IE vs Everyone Else
I just came off a full day fighting with a dynamic table addition, and I thought I'd go ahead and save someone else the pain.
I have a table, and I want to add rows via JavaScript when the user clicks a button. I created a function that did this. Since I develop against FireFox, I usually cross my fingers, load in IE for testing, and hope for the best.
Well, hope is, as they say, as hollow as fear.
the following function worked in FF, Opera, and Safari
-
function addRow() {
-
var tbl = document.getElementById('mytable');
-
var row = document.createElement("tr");
-
var td = document.createElement("td");
-
var input = document.createElement('input');
-
-
td.appendChild(input);
-
row.appendChild(td);
-
tbl.appendChild(row);
-
}
This created a new row in my table in FireFox and the like with a textfield in it. I've stripped out a lot of the extraneous properties and such, although I did add an onkeypress event to the field, twelve different fields, two select elements, and three text nodes.
Then I ran it in IE7, and nothing happened when I clicked the button. Or so it seemed. When I posted the form these were contained in, the new fields were there in the POST array, but nothing appeared on the screen.
After spending hours upon hours puzzling, googling, and trying different things, I found this:
http://msdn2.microsoft.com/en-us/library/ms532998.aspx
Which basically tells you what I am about to, but they do it in more detail. IE7 exposes a TOM (Table Object Model) that allows you to do what I wanted to very easily, except that the TOM doesn't work in any other browser. They also offer a standard DOM methodology, which is what my problem was. Here's the code that works in both IE and FireFox (untested in the others):
-
function addRow() {
-
-
var tbl = document.getElementById('mytable');
-
var tbody = document.createElement('tbody');
-
var row = document.createElement('tr');
-
var td = document.createElement('td');
-
var input = document.createElement('input');
-
-
td.appendChild(input);
-
row.appendChild(td);
-
// Thanks to Keith over at Etheric Arts for pointing out this line had a typo:
-
// tbody.appendChild(td); (Oddly enough, Firefox will add the row for you, IE will not)
-
-
// It should be:
-
tbody.appendChild(tr);
-
-
tbl.appendChild(tbody);
-
}
Hat-tip: Keith Moulton (Link:Etheric Arts)
See, the problem here was that I was adding a tr, td, and cell contents, but no tbody element to contain them. IE 7 was enforcing standards on me that FireFox and the others overlook.
While it was a frustrating lesson, it was a powerful one. Hope it helps someone else in need.
~A!