Click to See Complete Forum and Search --> : document.write problem


kurniawandie
01-30-2004, 12:28 AM
Hello Guys,

This is the first time I send a message in this forum. I am a newbie in javascript, so I am not sure if it is a bug, a limitation or just an incompatibility between IE and mozilla.

Below is the script from Internet and World Wide Web:How to program book. I modified some lines to identify the problem. It runs perfectly in Internet Explorer, but not in mozilla and netscape. I attached the javascript at the bottom of this message.

The javascript console gave 'functionA is not define'. However, when I delete line 5 'document.writeln("Hello")', it works in mozilla.

It would be very appreciated if you can help me with this problem.

Cheers,
Andie

***********************************************

<html>
<head>
<script language = "javascript">

function start()
{
document.writeln("Hello");
functionA();
document.writeln("Hello Again - It Works");
}

function functionA()
{
}
</script>

</head>
<body onload="start()">
</body>
</html>


***********************************************

fredmv
01-30-2004, 12:37 AM
Welcome to the forums.

The reason it isn't working as expected is because you are trying to write to the document using document.write after the page has loaded. This is a problem because when you call document.write after the page has loaded, it will erase all of the document's contents (hence that JavaScript error). What you want to be doing is calling document.write as the document loads as opposed to after the document loads. Therefore, simply change your script to this and it should work as expected:<script type="text/javascript">
//<![CDATA[
document.writeln("Hello.");
document.writeln("Hello again - it works.");
//]]>
</script>

kurniawandie
01-30-2004, 12:51 AM
But what happened if in functionA for example, I also want to print something.

<script language="javascript">

var x = 1;
function start() {
document.writeln(x);
x--;
functionA();
document.writeln(x);
}

function functionA() {
x++;
// want to check value of x
document.writeln(x);
}

</script>

If the purpose of the script is to evaluate the value of x, then we have to print it straightaway after we modify the value of x.

Cheers,
Andie

fredmv
01-30-2004, 12:57 AM
You could write it into a form element:<script type="text/javascript">
//<![CDATA[
var x = 1;

function report(v)
{
document.forms[0][0].value += 'x: ' + v + '\n';
}

function foo()
{
report(x);
x--;
bar();
report(x);
}

function bar()
{
x++;
report(x);
}

onload = foo;
//]]>
</script><form action="#">
<div>
<textarea rows="10" cols="50"></textarea>
</div>
</form>