0

JavaScript homework assignment requests "display the results in the document window". I am assuming it means to print out the JS answers on an HTML doc and not a pop-up.

I can get this code to work in the console, but have absolutely no idea how to get it to print on an HTML doc. From what I've read, using document.write is bad form and "return" doesn't seem to work. Any suggestions?

for (var i = 1; i <= 10; i++) {
  var mm = (i * 25.4);
  console.log (i + " inches = " + Math.round(100 * mm) / 100 + " millimeters"); 
}

Also, is there a way for all the numbers to print out the 10ths place integer? Notice in the results below, at "5 inches," it only prints the whole number, I'd like it to print 127.0 to keep the numbers consistent.

3 inches = 76.2 millimeters
4 inches = 101.6 millimeters
5 inches = 127 millimeters

Thanks in advance.

Padawan
  • 694
  • 1
  • 6
  • 19
  • Who said `document.write` is bad form? – Leeish Sep 08 '14 at 23:03
  • @Leeish I found out here, on these 3 links. http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice http://stackoverflow.com/questions/2559189/what-damage-is-done-by-document-write http://javascript.about.com/library/blwrite.htm – Padawan Sep 08 '14 at 23:09

1 Answers1

0

If you don't want to use document.write you can create a HTML element and then add a value to it with Javascript. Also you can use toFixed to format the number. For example:

HTML

<div id="hello"></div>

Javascript

document.getElementById("hello").innerHTML = "";
for (var i = 1; i <= 10; i++) {
    var mm = (i * 25.4);
    document.getElementById("hello").innerHTML += i + " inches = " + (Math.round(100 * mm) / 100).toFixed(1) + " millimeters <br />";
}