Static News Archive

   (3-May-09 17:52)  Internet explorer and Checkbox issues
IE is quite annoying when it comes to dynamically adding checkboxes and labels.

First off, if you are adding a checkbox to the DOM using javascript, and you want it to be checked by default, IE will only allow you to specify its checked state AFTER it has been added:

var newCB = document.createElement('input'); = "anotherCB";
newCB.type = "checkbox";
//newCB.checked = true; // This won't work here! we need to do it after the DOM append:
newCB.checked = true; // This will work

Now, say you want your checkbox to have a label - you need to set the 'for' attribute to the ID of the checkbox.
We can try to just set the property on the label object:

var label = document.createElement('label');
label.for =; // This will cause a JS error

Because 'for' is a javascript keyword, this won't work!
How about we try setAttribute?:

var label = document.createElement('label');
label.setAttribute('for',; // This will work in ff/chrome/opera - but not IE

As the comment says - this will still not work in IE.

The nicest cross browser solution is to use the 'htmlFor' property:

var label = document.createElement('label');
label.htmlFor =; // Success!


Post a comment     

<-  (5-Mar-09 14:54)  Javascript inheritan... (18-Jun-09 23:57)  Horrible CLR context...  ->