Tuesday, August 08, 2006

Dynamically create radio buttons with DOM (even in IE)

Currently, the way to create radio buttons dynamically in Internet Explorer is to use document.createElement("<input type='checkbox'>"). However, that is not very cross browser friendly. There is an easier way, that involves using jQuery and the correct DOM methods:

First of all, the HTML:

<form action="mypage.php">
<div id="radios"></div">
</form>

Now add the radio buttons to the radios element.

$(window).load(
 function()
 {
  $("#radios").each(
   function()
   {
    var radio = document.createElement("input");
    radio.name = "myradio";
    radio.type = "radio";
    radio.value = "radio1";
    this.appendChild(radio);
    for(i = 2; i < 10; i++)
    {
     radio = radio.cloneNode(true);
     radio.value = "radio" + i;
     this.appendChild(radio);
    }
    fixRadios(this.id);
   }
  )
 }
);

function fixRadios(parent)
{
 // uncheck existing radio buttons
 $("#" + parent + " input[@type=radio]").click(
  function()
  {
   
   $("[@name=" + this.name + "]").each(
    function()
    {
     this.checked = false;
    }
   )
   this.checked = true;
  }
 )
}

To see it in action: Dynamically create radio buttons with DOM

2 comments:

brito said...

Wouldn't you get a checkbox if you do: document.createElement("<input type='checkbox'>")? ;)

Sam said...

You would, but it would only work in Internet Explorer.