PDA

View Full Version : This should be easy but not for me.



Maxation
Aug 9th, 2009, 02:18 AM
I have written the following code which returns a simple times table. The problem is that I want the resulting times table written to the div id=results section in the body of the html page rather than writing it to another page. I hope that makes sense! Thanks in advance for any help.

<html>
<head>
<script type="text/javascript">
function timestable()
{
var num = parseInt(document.timesForm.times.value);
var counter = 1;
while (counter<=12)
{
document.write(counter+" X "+num+" = "+counter*num+"<br />");
counter++;
}
}
</script>
</head>

<body>
<form id="timesForm" name="timesForm">
<p>Enter the number here:&nbsp;&nbsp;<input type="text" id="times" /></p>
<p>
<input type="button" value="Show Times Facts"
onclick="timestable()"
/>
</p>
<div id="results">Times Facts</div>
</form>
</body>
</html>

tomws
Aug 9th, 2009, 03:47 AM
Wrapping your code in the appropriate code tags makes it much easier to read - just like it said at the bottom of the editing window where you created your post. Now for the problem...

Try innerHTML instead. (Not the best support, but still should work for this.) Cram all of the output into a variable and then dump that variable into the div. Something like this:

var myOutputDiv = document.getElementById('results');
var myOutput = '';
while (counter<=12)
{
myOutput += counter+" X "+num+" = "+counter*num+"<br />";
counter++;
}
myOutputDiv.innerHTML = myOutput;


EDIT: D'oh! You'll need to modify the form submit, too.

<form id="timesForm" name="timesForm" onSubmit="return false;">

Philip M
Aug 9th, 2009, 08:02 AM
document.write statements must be run before the page finishes loading. Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page. It cannot be used to update the content of your page after that page has loaded.

tomws - not sure what you mean by "not best support". innerHTML is supported by all modern browsers.

See: -http://www.quirksmode.org/dom/innerhtml.html
"The most obvious conclusion of these tests is that innerHTML is faster than "real" W3C DOM methods in all browsers. "

tomws
Aug 9th, 2009, 06:42 PM
tomws - not sure what you mean by "not best support". innerHTML is supported by all modern browsers.


Poor wording on my part. Thanks for the clarification.

Maxation
Aug 10th, 2009, 12:43 AM
Thank you for the help!