go****@quietbay.net wrote:
It would seem that when I assign an HTML entity to a form text
input using "inline" javascript that it will display properly.
But when trying to set it via a function call, the entity text
shows in the field instead of the symbol it represents. The
following example produces these results on Opera 8.5 and
IE 6.0
I am expecting the same results whichever way I set the
contents of "myText". Why, when choosing "function" does
"©" show in the field instead of the copy symbol? If
there is something obviously wrong... I cannot see it.
Any comments are appreciated.
<head>
<title>My Test</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
function set_it(obj)
{
obj.form.myText.value='©';
}
</script>
<form action="#" method="get">
<input name="myText" type="text" value="©" />
<input name="btn01" type="button" value="inline"
onClick="this.form.myText.value='©';"/>
<input name="btn02" type="button" value="function"
onClick="set_it(this);"/>
</form>
</body>
</html>
You are experiencing the difference between PCDATA and CDATA. The
contents of a SCRIPT element are specified in HTML (but not XHTML) as
being CDATA; literal character data where the only significant character
sequence is ' </', which may be taken as terminating the CDATA (this is
superficial description, refer to the section of the HTML specification
on 'types' for more detail).
On the other hand the contents of the value assigned to an event
handling attribute is PCDATA and is parsed by the HTML parser. The
parser will observe entities that it recognises, such as ©, and
substitute them with a known character. This will happen before any code
in the even handling attribute is shown to the javascript interpreter.
As you are using the copyright symbol it may be worth mentioning that
there was a release of Netscape 6.2 (hopefully now long dead) that would
refuse to execute javascript source that contained a literal copyright
symbol).
In any event, you should be able to use a literal copyright symbol in a
string literal in CDATA, but that might not be a good idea. So instead
you should probably use a javascript escape sequence in that context:
Hex escape = \xA9 Unicode escape = \u00A9
You can also use the javascript escape sequence(s) in the event handling
attribute value, as it would mean nothing to the HTML parser.
Richard.