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';
}

This entry was posted in Blog Posts and tagged , , . Bookmark the permalink.

4 Responses to Dynamic radio buttons in IE

  1. Dan says:

    Once again windows telling us what to do.

  2. WebDeveloper says:

    It’s just IE keeping it interesting.

  3. Flaszter says:

    Thanks it is working. When will the day come when the IE is not exist anymore!! IE is sucks!

  4. Cyrus says:

    I found that adding an onclick() to the radio button that sets radioButton.checked will also work in IE, although if you do that, you also need to add code to uncheck any other selected button in the group, since IE will not do that for you.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>