RSS

Tag Archives: create radio button

Dynamically create radio buttons in JavaScript

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";
radButton.name = "radSelect0";
someelement.appendChild(radButton);

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.

 
2 Comments

Posted by on April 26, 2009 in HTML, JavaScript

 

Tags: ,