Dynamic radio buttons in IE

Man do I hate IE.

You’d think that creating a radio button in javascript would be as easy as something like this:

var radioButton = document.createElement('input');
radioButton.id = 'RadioButtonList_1';
radioButton.name = 'RadioButtonList';
radioButton.type = 'radio';
parentElement.appendChild(radioButton);

but, no - that doesn’t work, thanks to IE not allowing the name attribute to be set for dynamically created elements.
So, instead, you need to do something like this:

var radioButton;
try {
    // This is the only way you can set the "name" attribute in IE, but it will fail in other browsers
    radioButton = document.createElement('<input id="RadioButtonList_1" name="RadioButtonList" type="radio" />');
} catch() {
    // The above will fail if not in IE, so try it the correct way here
    radioButton = document.createElement('input');
    radioButton.id = 'RadioButtonList_1';
    radioButton.name = 'RadioButtonList';
    radioButton.type = 'radio';
}

2 Comments

  1. Posted July 30, 2007 at 12:23 pm | Permalink

    Once again windows telling us what to do.

  2. WebDeveloper
    Posted August 8, 2007 at 8:15 am | Permalink

    It’s just IE keeping it interesting.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*