Reputation:
I'm working on a FizzBuzz solution. I had it working fine when I called the function onload and set the input variable with a prompt (see comments in my code), but when I added a form, called the function onclick, and tried to set the variable using getElementById, my function would not print to the div. In the original version, the output is visible after the function completes. In the updated version, the output flashes briefly and then disappears. It is as if I am immediately refreshing the screen. Any suggestions? Thanks
<script>
function fizzbuzz(){
// var num = prompt("Enter a number: ");
var num = document.getElementById("number").value;
var div3 = document.getElementById("div3");
for(var i=0; i<num; i++){
if (i%3===0 && i%5===0){
div3.innerHTML = div3.innerHTML+"Fizz Buzz<br>";
}else if (i%3===0){
div3.innerHTML = div3.innerHTML+"Fizz<br>";
}else if (i%5===0){
div3.innerHTML = div3.innerHTML+"Buzz<br>";
}else{
div3.innerHTML = div3.innerHTML+(i+1)+"<br>";
}
}
}
</script>
</head>
<body>
<!--body onload = "fizzbuzz()"-->
<div id = "div1">
<h1>Fizz Buzz</h1>
<form>
<p>Enter a number:</p><p><input type="text" name="number" id="number"/><input type="submit" value="Submit" onclick = "fizzbuzz()"/></p>
</form>
<div id="div3"></div>
</div>
</body>
Upvotes: 1
Views: 84
Reputation: 887415
Your <input type="submit">
is submitting your form – and reloading the page – after your click handler runs.
You need to return false
from the handler to prevent that.
Upvotes: 0
Reputation: 104775
Your button is of type submit
- which is causing the page to post back / refresh, hence why you see it flash. Either prevent the default action with e.preventDefault
or change your input
to type of button
, or use return false;
Prevent Default:
<!--Pass in event to the func-->
<input type="submit" value="Submit" onclick = "fizzbuzz(event)"/>
//Use it
function fizzbuzz(e) {
e.preventDefault();
...
}
Or use type button
<input type="button" value="Submit" onclick = "fizzbuzz()"/>
Or return false
function fizzbuzz(e) {
...
...
return false;
}
Upvotes: 2