Adding Dynamic Input Elements In IE Fails To Update Element's Array...

Posted by Dan on Oct 28, 2005 @ 2:35 PM

If you've ever used the createElement to dynamically add form elements to a page, you may have run into this problem before. You're working on a form and need to add some dynamic checkbox elements to the DOM on-the-fly. The code works great in Firefox, but in IE the fields are only displayed—they're not getting added to the named element's field (document.formName.fieldName) array.

In order to resolve this problem, you need to add a little DOM hack for Internet Explorer. When you invoke the createElement() method you must specify the name of the tag in the string:

var oField = document.createElement("<input name=\"isCheckboxField\" />");

The problem is this only works in IE. To work around this just create the input element using the following code:

var oField = document.createElement((document.all) ? ("<input name=\"isCheckboxField\" />") : "input");
var oField.setAttribute("name", "isCheckboxField");

This will update IE's internal name space so that when you try to access the field via the document.formName.isCheckboxField element, you'll get the correct results. Now when you call alert(document.formName.isCheckboxField.length); you'll get the correct value containing the number of dynamic elements that have been added to the DOM.

I've run into this problem from time-to-time and couldn't remember what I did to fix the problem.

NOTE:
If you're having this problem in Firefox/Gecko, make sure that your <form> tag is not incorrectly inserted between a <table> and a <tr> tag.
Categories: JavaScript

Add Comment

Leave this field empty