Yet another programmer blogging about code

Internet Explorer 7 and dynamically created form inputs

Apparently, Internet Explorer 7 is stupid. I mean, it lets you create a form input element dynamically, and add it to a form, but the form doesn’t know it by name. And I only just found this out!

OK, so I probably haven’t been creating form fields dynamically in the browser in JavaScript all that much, preferring to do that in a server-side script, so I didn’t know that “this behaviour is by design“:

Microsoft JScript allows you to change the name at run time. This does not cause the name in the programming model to change in the collection of elements, but it does change the name that you use for submitting elements.

What that means is that the following piece of code fails, because the elements collection of the form doesn’t know the input element by name:

var panel = document.getElementById("panel"),
    form = document.createElement("form"),
    input, p;

// populate form and add to panel
p = document.createElement("p");
p.appendChild(document.createTextNode("From: "));
input = document.createElement("input");
input.type = "text"; = "from";

form.elements.from.focus();  // fails in IE7!

Of course, Microsoft have a workaround:

To create an element with a NAME attribute in earlier versions of Internet Explorer, include the attribute and its value when you use the createElement method.

And of course, that breaks in any reasonable browser! But all is not lost; it’s clear that a quick hack can save the day here:

// hack to fix IE<=7 name weirdness for dynamically created form elements;
// see but have a hanky ready
if (typeof form.elements.from == "undefined") {
    form.elements.from = input;

There, job is done, and it better not be undone by bloody IE10.