July 15th, 2009 | Joel | Comments#comments">Comments
I hope to make this blog useful both from an entrepreneurial standpoint and a web development standpoint. Here is a more technical entry.
Problem

I just had to solve an issue I was having with input elements dynamically inserted via JavaScript and it took me an hour or so to find the solution, so I thought I’d post it here for the opportunity it may help someone else reach the solution faster.

The problem arose when I discovered that a tool I had developed which uses AJAX extensively to change the options available to the user depending on other options was not working in Internet Explorer (testing was on IE7).
It was not immediately obvious that it was IE’s broken implementation of the DOM which was causing the issue. The first thing I discovered was that the serialize() function was not including elements. I then discovered that this was only when the elements had been inserted dynamically via JavaScript. I then happened to find a post by Aaron Gustafson on Easy! Reader entitled “Death to bad DOM implementations”, which outlined the very issue.
The problem is that IE disallows changing of the name attribute of elements after the element has been created. Thus the usual method I use won’t work:
$(document.createElement('input')).attr("name", "email"));

The reason is that the input element is created and then the name attribute is added once the element already exists. IE doesn’t like this.
Solution
In the comments of Aaron’s post, Chris Purcell has a very nice function to use which solves the problem:

document.createNamedElement = function(type, name) {
    var element;
    try {
        element = document.createElement('<'+type+' name="'+name+'">');
    } catch (e) { }
    if (!element || !element.name) { // Not in IE, then
        element = document.createElement(type)
        element.name = name;
    }
    return element;
}
So you can then simply do (for form elements):

$(document.createNamedElement('input', 'email));

If that helps even just one person out there I’ll be very happy. Also, documenting it reinforces it in my memory for the future.
If you find my posts useful, you should follow me on Twitter! :)

blog comments powered by Disqus