Dynamic form issues in IE and Safari

In the world of rich web applications, browser bugs and incompatibilities are the number one killer of productivity, next to YouTube, Facebook, and Myspace. Like most web developers, I have come to realize most of those issues arise from IE and Safari. Today I stumbled upon another interesting problem when trying to implement some dynamic forms.

Take for instance the following code snippet:

 
//Create form elements
var form1 = Element.create('form', {name: 'test_form'});
var input1 = Element.create('input', {type: 'text'});
var input2 = Element.create('input', {type: 'text', name: 'input2'});

//Append inputs to form
form1.appendChild(input1);
form1.appendChild(input2);

//Append form to document
document.body.appendChild(form1);

//Set input1's name
input1.name = "input1";

//Check if form picked up on name change
alert(form1.input1);
alert(form1.input2);

If you aren’t familiar with Prototype, this may be a bit hard to understand, but here is what is going on. I am creating a form with two inputs. Both inputs’ names are set in Javascript, but one is set before the form is appended to the document body, and the other is set after.

This code works fine in Firefox, but IE and Safari fail to note the name change, and don’t add the element’s property to the form element.

I created a workaround for a different Safari issue a few months ago, but it works well for this issue as well. The only requirement is your application must be using Prototype.

Form.prepare = function(form){
    var elements = Form.getElements(form);
    for(var i=0, ii=elements.length; i++){
        var elm = elements[i];
        if(elm.name && !form[elm.name]){
            form[elm.name] = elm;
        }
    }
}

In the above example, this would be called before we wished to access the form elements, alert(form1.input1).