I've done FizzBuzz several times but never had this problem. Perhaps, it is something fundamental about for-loops that I don't understand. For some reason, the code below runs 10x longer than it should (well, than I think it should). If the user enters 20, it runs to 200. I fixed the problem by setting i = 0; i < num and then printing i+1 to my div, but I still don't understand why the original code does not work as expected. And while I'm at it, I might as well admit that I still can't set up JSFiddle properly. http://jsfiddle.net/nngrey/hA4pg/ (This does not run at all.) So any thoughts on that would also be appreciated. Thanks!
<head>
<title>Fizz Buzz</title>
<script>
function fizzbuzz(){
var num = prompt("Please enter a number between 1 and 100: ");
for(var i=1; i<num+1; i++){
if (i%3===0 && i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz Buzz</p>";
}else if (i%3===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Fizz</p>";
}else if (i%5===0){
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>Buzz</p>";
}else{
document.getElementById("div1").innerHTML = div1.innerHTML+"<p>"+i+"</p>";
}
}
}
</script>
</head>
<body onLoad = "fizzbuzz()">
<div id = "div1">
<h1>Fizz Buzz</h1>
</div>
</body>
Fizz Buzz
"; ? I am not following your advice about declaring the div1 variable. I'm creating an id in my html but I don't think that's what you mean. – Oct 25 '13 at 04:36Fizz Buzz
"; Better? – Oct 25 '13 at 04:46