On 11/03/2006 17:41, Chameleon wrote:
[snip]
Other than the invalid markup?
[snip]
function hi() {
html = document.getElementById('html').checked;
alert(html);
}
</script>
<input type=checkbox id=html onchange="hi();" checked>HTML format
The issue here is with IE's tendency to create global variables using
the id attribute values of elements, and the variable in the function, hi.
When IE parses an element with an id attribute, it creates a global
variable with the same name as that value and assigns to it a reference
to the element. That is, after parsing the markup in your example, there
will be a global 'html' variable that references the checkbox.
These global variables are read-only and attempting to assign any value
to them will result in an error, hence your problem. However, if a
variable is declared using a var statement, this will override IE's
normal behaviour.
So, if your intention was for 'html' to be a global variable, explicitly
declare it so:
var html;
function hi() {
/* ... */
}
If not, and there's indication that it should be, make it a local variable:
function hi() {
var html = /* ... */
}
A few other notes:
Before using DOM methods like getElementById, one should test for them.
Testing the return value isn't a sound defensive strategy, too:
function hi() {
var html;
if (document.getElementById) {
html = document.getElementById('html');
}
if (html) {
alert(html.checked);
}
}
However, the use of getElementById isn't necessary in your case:
function hi(html) {
alert(html.checked);
}
<input type="checkbox" onchange="hi(this);" checked>
In the snippet above, the this operator will refer to the checkbox, so
this reference can be passed to the function directly.
Hope that helps,
Mike