Dynamic Name Input Attributes with IE and jQuery Clones

Posted on March 01, 2010

Wow, look at me getting all nerdy all of a sudden.

We all know that IE sucks pretty hard.  For work I'm charged with supporting IE7 in our Javascript framework, based on jQuery.  We have a javascript powered template engine that duplicates content for n-numbers of data collections.  So, for example, you might end up getting four sets of data, one for each url, which includes something like a chunk of review text and the url itself.  

The template would then go about cloning the initial html structure four times, thus producing four distinct chunks of html.  The template system renames each chunk's element's IDs and the names of any form inputs in order to ensure that everything remains kosher for submission or DOM manipulation.

Problem is, Internet Explorer 7 doesn't support programmatically modifying the names of the elements.  No matter how many times you try to modify the attribute with jQuery, or how many times you try to read the HTML, you end up with the original name.  This blows.

So best solution I've found, if you're programmatically modifying the name as we were, is to parse out the outerHTML, regex replace the name to your desired name, then use jQuery to replace the input in question with the parsed HTML.  Certainly not the most elegant thing in the world, but it is a transparent solution that you can plug into your element cloning process.

Here's what I did, basically:

$(some_cloned_element).each(function(i, elem){
    var newName = "yay_i_love_my_new_name";
    if ($.browser.msie === true){ // evil browser sniffing *cries*
            this.outerHTML.replace(/name=\\w+/ig, 'name='+newName+'_'+i)
    } else {

Or whatever. You get the idea. Basically creating fresh elements for IE to get itself attached to rather than modifying a clone in-place.  Works well enough.

comments powered by Disqus