I have a tic tac toe program. The game board has a table with 9 cells. The cells need to be clickable, but when I click them, nothing happens. Cells are created in line 25. The cellClicked function on line 10 is supposed to execute, but line 12 appears to not execute. Any ideas? Thank you.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Tic Tac Toe</title>

<script type="text/javascript">
//<![CDATA[

function cellClicked () 
{
   alert ("Cell Clicked");
}


function setUpPage ()
{
    document.write ('<table width=750 height=750 bgcolor="#FF0000" border="0">');

    for (i = 0; i < 3; i++)
	{
	   document.write("<tr>");
	   for (j = 0; j < 3; j++)
	   {
	       document.write ('<td width=250 height=250 bgcolor="#00FF00" onclick="cellClicked()">X</td>');
	   }
	   document.write ("</tr>");
	}
			
	document.write ('</table>');
}
//]]>
</script>


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

once the page has finished loading, if you call document.write you "destroy" the current document, and a new document will be created containing the new content you are writing. In your case, the "cellClicked" function exists in the original/old document (before document.write is executed), but since you call document.write via setUpPage after the page has finished loading:

<body onload="setUpPage()">

you "destroyed" your cellClicked function. Thus, instead of what you have, try:

...
<body>
<script type="text/javascript">setUpPage ()</script>
</body>
...

so that document.write is executed before the original document finishes loading.

commented: Thank you. +11

once the page has finished loading, if you call document.write you "destroy" the current document, and a new document will be created containing the new content you are writing. In your case, the "cellClicked" function exists in the original/old document (before document.write is executed), but since you call document.write via setUpPage after the page has finished loading:

<body onload="setUpPage()">

you "destroyed" your cellClicked function. Thus, instead of what you have, try:

...
<body>
<script type="text/javascript">setUpPage ()</script>
</body>
...

so that document.write is executed before the original document finishes loading.

Awesome. Thank you very much. That worked.

you are welcome

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.