DOM-created radio buttons don't work in IE6


This is a nasty little known problem with IE when creating radio buttons using document.createElement(). IE actually creates the buttons, but they can’t actually be selected by the user.

The problem is that aparently IE doesn’t let you set the name attributes of elements after they’ve been created. If you update the name attribute, it’ll change the name of the variable that’s sent when the form is posted, but it won’t change the name that the page uses to refer to the element. This isn’t really such a big deal for other form elements, particularly if you’re accessing them by ID rather than name, but because the radio buttons rely on the name attribute to tell which buttons are grouped together, not having a name set means the buttons don’t belong to any group.

I saw a work around using innerHTML in a span and using setAttribute which I didn’t try out. I might try the setAttribute method on Monday because if that works it’d actually be more standards friendly (and simple) than what I’m currently doing.

The work around I went for was using an IE only version of createElement. This included using the first bit of browser sniffing not based on the “can you do this?” mentality that I’ve done in quite a while. :/

  1. var myradioButton;
  2. if(!document.addEventListener) {
  3.  // IE hack
  4.   myradioButton= document.createElement("<input name=\"" + groupName + "\"/>");
  5. } else {
  6.  myradioButton= document.createElement("input");
  7. }
  8. myradioButton.type = "radio";
  9. = "mygroup";
  10. panel.appendChild(myradioButton);
  11. myradioButton.value = "myvalue";

I really hate having to do stuff like this. It makes my code more brittle and harder to maintain. There’s a good chance this bit of code will hang around longer than the current set of bugs in IE and quite possibly longer than me in my current job. Maybe one day there will be some device that will fail the browser sniffing code I’ve written for reasons other than “being IE” and that’ll mean my W3C piece of incompatible code won’t work.

Posted on 23 Oct 04 by Helen Emerson (last updated on 23 Oct 04).
Filed under Browser quirks