Wednesday, July 16, 2008

Gotcha Of The Day - Setting The HTML Name Attribute Dynamically

I've now been bitten by this one twice: First, I created an iframe dynamically (by using JavaScript and the DOM) and for some reason, it wasn't submitting to the right target. And then last night, a set of radio buttons I created using the JavaScript DOM didn't work in IE. They rendered, but when you clicked on them, nothing happened.

I was doing something like:

  var r = document.createElement("input");
  r.setAttribute("name", "RadioButtonGroupName");
  r.setAttribute("type", "radio");
  r.setAttribute("value", "Whoo!");

It turns out, for IE, setting the name attribute dynamically isn't possible. At least not through obvious means. Instead, you have to do:

  var r = null;
  try {
     // For IE
     r = document.createElement("<input name='" + name + "'>");
  } catch(ex) {
     // For browsers that work
     r = document.createElement("input");
     r.setAttribute("name", name);
  r.setAttribute("type", "radio");
  r.setAttribute("value", "Whoo!");

I know, how ugly is that? But, at least there's a work around that lets you stay in the world of DOM without hard coding things too badly.


  1. Anonymous2:37 PM

    Welcome to the painful world of IE development!

    This is just one of the dozens of attributes you CANT set in IE.

    See here for complete details.

    There's actually a lot of good info on this site. I highly recommend an extensive read.

  2. That's a great article, thanks. I noticed my `for' attribute wasn't working either - and now I know why.

    This is a world I would have done just fine not being welcomed to ;-)