Very new to javascript and html-type stuff. I wanted to just make a quick example using input from a user and outputting it into a table. I’m having trouble getting the window prompt to actually come up though. I imagine there is somethign very obvious that I am doing wrong but I’m not currently seeing it…I am taking a class in school but this isn’t a homework assignment, just exercises I am doing on my own.
Is this something with the while loop? Any suggestions as to how I should keep prompting the user until they state otherwise?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mileage Record</title>
<style type = "text/css">
table {
width:300px;
border-collapse:collapse;
background-color:lightblue;
}
table, td, th {
border: 1px solid black;
padding: 4px;
}
th {
text-align: left;
color: white;
background-color: darkblue
}
tr.oddrow {
background-color: white;
}
</style>
<script>
var milesDriven;
var gallonsUsed;
var mpg;
var anyMore;
document.writeln("<table>");
document.writeln("<thead><tr><th>Miles Driven</th>");
document.writeln("<th>Gallons Used</th>");
document.writeln("<th>MPG</th>");
document.writeln("</tr></thead><tbody>");
while (anyMore == true) {
milesDriven = window.prompt("How many miles did you drive?");
gallonsUsed = window.prompt("How many gallons did you use?");
mpg = milesDrive/gallonsUsed;
document.writln("<tr><td>" + milesDriven + "</td><td>" +
gallonsUsed + "</td><td>" + mpg + "</td></tr>");
anymore = confirm("Do you have any more data to input?");
}
document.writeln("</tbody></table>");
</script>
There are several problems in the approach. You should not use
document.writeln()to modify document content. Instead, create elements and add them to the document tree. A good JavaScript tutorial should tell you how to do that. It will also explain that identifiers are case-sensitive, so you can’t just writeanyMorehere andanymorethere. You also have other typos in identifiers. And since an undefined value does not equaltrue, your loop is not executed ever.