Site Navigation

Tuesday, November 6, 2007

bug 299 - setAttribute "checked" does not work in IE

Issue: #299
Affects: IE5, IE5.5, IE6, IE7
Fixed In: IE8 RC1

If you use the DOM Methods to build up new content for your page, be aware that in IE, you can't pre-check a radio button or a checkbox using .setAttribute('checked', 'checked'); or even myCheckBoxObject.checked = true; *unless* you add the element to the page first.

Example:

<script type="text/javascript">
var cb1 = document.createElement('input');
cb1.setAttribute('checked', 'checked');
document.getElementsByTagName('body')[0].appendChild( cb1 );
</script>


In all other browsers, this would add the checkbox to the page, pre-checked.

Known Workarounds: Two. You can set the checked attribute after you've appended your element to the DOM (so it will flash momentarily before being checked), or, you can call cbObj.setAttribute('defaultChecked', 'defaultChecked'); which will also work.

Note, when setting the checked, or the defaultChecked attribute, any value for "true" will work.

Example Workaround Code:

<script type="text/javascript">
var cb1 = document.createElement('input');
cb1.setAttribute('defaultChecked', 'defaultChecked');
document.getElementsByTagName('body')[0].appendChild( cb1 );
</script>


Related Issues: bug 235, bug 237, bug 242.