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 http://stackoverflow.com/questions/118693/how-do-you-dynamically-create-a-radio-button-in-javascript-that-works-in-all-br, 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:
http://www.quirksmode.org/bugreports/archives/2005/10/Radios_name_attribute_doesnt_work_when_using_appen.html
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html

No comments:

Subscribe in a Reader