Reputation: 103
Any chance someone can see why this isn't working and explain it to me?
I've tried this locally (using xampp) and on JS Bin. Using JS Bin it appears that the div DOES hide, but then comes right back.
Here is my html/code:
<div id="maxnum">
<p>What number would you like to count to?</p>
<form>
<input type="number" name="count-to" id="countnum">
<button onclick="alts()">This Number</button>
</form>
</div>
<script>
function alts(){
mnum=countnum.value;
document.getElementById('maxnum').style.display = 'none';
}
</script>
Upvotes: 0
Views: 462
Reputation: 45135
The clicking the button in your form
is submitting the form, which cause the page to reload (and hence your hidden div reappears). You need to return false
from the handle to stop that from happening.
For example:
function alts(){
mnum=countnum.value;
document.getElementById('maxnum').style.display = 'none';
return false; // this stop submission
}
And:
<button onclick="return alts()">This Number</button>
Or if you intention is to not ever submit the form, then you don't actually need the form
tag at all and removing it will solve the problem.
Or, as @WookieCoder pointed out, you can use input
with type button
instead of button
like this:
<input type="button" onclick="alts()" value="This Number"/>
(note using type="submit"
would give you a button that does submit the form).
You can actually even specify a type for the button
. The default in most browsers is submit
, but you can do this:
<button type="button" onclick="alts()">This Number</button>
And have a button
that behaves like a button
instead of a submit
.
Upvotes: 3
Reputation: 382
It comes back because of PostBack.
Return false after you call alts(). It'll prevent post back
<button onclick="alts(); return false;">This Number</button>
Upvotes: 0