Sunday, December 21, 2008

How do you dynamically create a radio button in Javascript that works in all browsers?

Well, another bug from IE is the createElement() method. Unlike other browsers, it works weirdly by setting the default input "type" attribute to "text". Thus, you cannot change the "type" attribute to other value beside "text". Have a look on the documentation of this method from msdn microsoft.
Try the following code in IE by yourself, you might end up with the weird behavior on IE.

   var radio = document.createElement("input");
   radio.setAttribute("type", "radio");
   radio.setAttribute("name", "test_1");
   radio.setAttribute("value", "yes, it doesn't work!");
   radio.setAttribute("checked", "checked");

To solve this this problem, you need to pass the entire html code of element you want to create to createElement() method.

   var radio = document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='First Choice'>");

The following code I quote from, and it works across all browsers.

   function createRadioElement( name, checked ) {
   var radioInput;
      try {
         var radioHtml = '<input type="radio" name="' + name + '"';
         if ( checked ) {
            radioHtml += ' checked="checked"';
         radioHtml += '/>';
         radioInput = document.createElement(radioHtml);
      } catch( err ) {
         radioInput = document.createElement('input');
         radioInput.setAttribute('type', 'radio');
         radioInput.setAttribute('name', name);
         if ( checked ) {
            radioInput.setAttribute('checked', 'checked');

      return radioInput;

Here are some other references:

Subscribe in a Reader