Dynamically create radio buttons in JavaScript

26 Apr

The initial task sounds trivial but when I tried to test the following code in IE the radio button seemed to be totally uncheckable.

var radButton = document.createElement("input");
radButton.type = "radio"; = "radSelect0";

It turned out that there is a problem in IE and the name and selected properties can’t be set dynamically.

The only way round is to create radio button using innerHTML property.

function createRadioButton(elementname, ifchecked) {
   var radiobutton = '<input type= "radio" name="' + elementname + "'";
   if ( ifchecked) radiobutton +=  ' checked="checked"';
   radiobutton += '/>';

   document.createElement('p').innerHTML = radiobutton;

Or it’s also possible to combine both ways:

function createRadioButton(elementname, ifchecked) {
   var radioButton; 
   var ifChecked = false; 
   try { 
      radioButton = '
      if ( ifChecked ) { radioButton += ' checked="checked"'; } 
      radioButton += '/>'; 
      radioButton = document.createElement(radioButton); 
   } catch( err ) { 
      radioButton = document.createElement('input'); 
      radioButton.setAttribute('type', 'radio'); 
      radioButton.setAttribute('name', "radSelect0"); 
      if ( ifChecked ) { radioButton.setAttribute('checked', 'checked'); } 
   document.createElement('p').innerHTML = radioButton;

Hope it helps to save someone’s time.


Posted by on April 26, 2009 in HTML, JavaScript


Tags: ,

2 responses to “Dynamically create radio buttons in JavaScript

  1. Nick

    April 26, 2009 at 5:23 pm

    Don’t you just love IE? ugh! well the good news is that this is fixed in IE8 but until then you’ll need this workaround code for radio buttons (AND CHECKBOXES).

    You can also set the “defaultChecked” attribute to overcome this issue.

    See this bug filing for details

    actually the bug site above lists dozens and dozens of IE specific bugs – if you don’t know them all off by heart. ๐Ÿ˜‰

  2. Dasha

    April 27, 2009 at 12:49 am

    Me? I adore IE ๐Ÿ˜€

    Yep, IE8 seems to be a great thing but still there is too much of IE6 and we still have to support it.

    Now I am testing another weird bug with setting up selectedIndex of dynamically populated select.

    Thanks for the link but haha I keep it opened all the time ๐Ÿ™‚

    Thanks for your reply!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: